B4A Library FirebaseAdMob2 - Google Mobile Ads SDK v20+

Status
Not open for further replies.
This is a wrapper for Google Mobile Ads v20+ SDK.
It is a modified version of FirebaseAdmob (1).
This library works with Google Mobile Ads v20+. The previous library works with v19-.

Note that you can use FirebaseAdMob2 without creating a Firebase account.

It supports banner ads and interstitial ads.

Instructions:
1. Add to manifest editor:
B4X:
CreateResourceFromFile(Macro, FirebaseAnalytics.GooglePlayBase)
CreateResourceFromFile (Macro, FirebaseAdMob.FirebaseAds)
AddReplacement($ADMOB_APP_ID$, ca-app-pub-12673333333~67613333333)

2. Initialize MobileAds:
B4X:
Dim m As MobileAds
Wait For (m.Initialize) MobileAds_Ready
m.SetConfiguration(m.CreateRequestConfigurationBuilder(Array("77A04EE40B2AFED2AFC67701365187EC"))) 'optional. Array with test device ids. See unfiltered logs to find id.

3. Banner ad:
B4X:
Sub Activity_Create(FirstTime As Boolean)
   Dim AdaptiveSize As Map = GetAdaptiveAdSize
   'Add Private BannerAd As AdView in Globals sub
   BannerAd.Initialize2("BannerAd", "ca-app-pub-3940256099942544/6300978111",AdaptiveSize.Get("native"))
   Activity.AddView(BannerAd, 0, 0,  AdaptiveSize.Get("width"), AdaptiveSize.Get("height"))
   BannerAd.LoadAd
End Sub

Sub GetAdaptiveAdSize As Map
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim AdSize As JavaObject
    Dim width As Int = 100%x / GetDeviceLayoutValues.Scale
    Dim Native As JavaObject = AdSize.InitializeStatic("com.google.android.gms.ads.AdSize").RunMethod("getCurrentOrientationAnchoredAdaptiveBannerAdSize", Array(ctxt, width))
    Return CreateMap("native": Native, "width": Native.RunMethod("getWidthInPixels", Array(ctxt)), _
        "height": Native.RunMethod("getHeightInPixels", Array(ctxt)))
End Sub

Sub Ad_ReceiveAd
    Log("Adview received")
End Sub

Sub Ad_FailedToReceiveAd (ErrorCode As String)
    Log("Failed: " & ErrorCode)
End Sub

Sub Ad_AdClosed
    Log("Closed")
End Sub

Sub Ad_AdOpened
    Log("Opened")
End Sub

4. Interstitial ad:
B4X:
'Add Private iAd As InterstitialAd in Globals sub
iad.Initialize("iad", "ca-app-pub-3940256099942544/1033173712")
iad.LoadAd


Sub iAd_ReceiveAd
    Log("IAd received. Now wait for the right moment to show the ad.")
    If ad.Ready Then
       ad.Show 'bad example. You should instead wait for the correct time and show it when it makes sense.
    End If
End Sub

Sub iAd_FailedToReceiveAd (ErrorCode As String)
    Log("Failed: " & ErrorCode)
End Sub

Sub iAd_AdClosed
    Log("Closed")
End Sub

Sub iAd_AdOpened
    Log("Opened")
End Sub

Libraries developers:
Source code: https://github.com/AnywhereSoftware...esoftware/b4a/admobwrapper/AdViewWrapper.java
It depends on: C:\Android\extras\b4a_remote\com\google\android\gms\play-services-ads-lite\20.0.0\unpacked-play-services-ads-lite-20.0.0\jars\classes.jar

For more advanced features, use FirebaseAdMob2 with AdsHelper: https://www.b4x.com/android/forum/t...irebaseadmob2-google-mobile-ads-v20-0.129696/

Updates:

v2.13 - Internal library in B4A v10.9. Deprecated Google consent SDK was removed as it caused app to be rejected.
v2.12 - Fixed typo in MobileAds.SetConfiguration (it was SetConfigutation by mistake).
 
Last edited:

asales

Well-Known Member
Licensed User
Longtime User
Great. Thanks!

Some questions:

1 - As the smart banner was deprecate in favor of adaptive banner
Can I still use this code to adaptive banners?

2 - There is no more method IsInitialized in Instertitial Ad.
I use this method before to avoid errors in show the ad. Now I need to use only the Ready method?

2 - Do you plan to update this lib with Admob Consent, Native, Rewarded (video and interstitial) and other ads types?
 

Scantech

Well-Known Member
Licensed User
Longtime User
Is this mandatory update to follow Google guidelines or can I just leave my app with the older firebaseadmob library?

Please add the IsInitialized . Thanks
 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
1. I've updated the code to use the adaptive banner size.
2. V2.11 is released with an IsInitialized method.
3. The same consent code as before will work with the new library.
4. Native and other types of ads can be added with JavaObject. This is more practical as Google changes the API quite frequently.

Is this mandatory update to follow Google guidelines or can I just leave my app with the older firebaseadmob library?
Make sure not to update the sdk manager. For now you can keep using the old API.
 

Lucas Eduardo

Active Member
Licensed User
4. Native and other types of ads can be added with JavaObject. This is more practical as Google changes the API quite frequently.

Understood, but can you start the code to help me, for example to App Open Ads?

Thank you.
 
Last edited:

tufanv

Expert
Licensed User
Longtime User
1. I've updated the code to use the adaptive banner size.
2. V2.11 is released with an IsInitialized method.
3. The same consent code as before will work with the new library.
4. Native and other types of ads can be added with JavaObject. This is more practical as Google changes the API quite frequently.


Make sure not to update the sdk manager. For now you can keep using the old API.
So, with consent, we will continue to request ads with builder right ?
 

Douglas Farias

Expert
Licensed User
Longtime User
Hi All.
First.. thanks a lot for this library @Erel .
Native and other types of ads can be added with JavaObject.
Could you please post an initial code to help with javaobject? I believe that if you start the example, i or someone else will be able to finish, similar to what I did with some other ad libs here on the forum.

today admob offers the following types, in addition to the banner and interstitial.
- Opening the app
- Awarded interstitial (beta)
- Awarded
- Advanced native

thx again! :)
 

Rubsanpe

Active Member
Licensed User
Hi, I think there is a mistake in the name of the function "SetConfigutation" of MobileAds. Shouldn't it be "SetConfiguration"?

Rubén
 

andymc

Well-Known Member
Licensed User
Longtime User
I may be doing something wrong, but I'm getting this error trying to update my apps to use this library from the older version:
I cut and pasted the lines into the manifest editor and replaced the id value with my own ad id.

java.lang.NoSuchMethodError: No static method getRewardedVideoAdInstance(Landroid/content/Context;)Lcom/google/android/gms/ads/reward/RewardedVideoAd; in class Lcom/google/android/gms/ads/MobileAds; or its super classes (declaration of 'com.google.android.gms.ads.MobileAds' appears in base.apk)
 

Erel

B4X founder
Staff member
Licensed User
Longtime User

samannnn

Member
Why it is not support reward? I have lots of app and google tell me that you should change old admob sdk to new one. It takes lots of times to chage all cods, could you tell me simple way for update sdk with less changes in my app?
Apps are not compatible with b4xpage and its difficult to use adhelper library.
 

mcqueccu

Well-Known Member
Licensed User
Why it is not support reward? I have lots of app and google tell me that you should change old admob sdk to new one. It takes lots of times to chage all cods, could you tell me simple way for update sdk with less changes in my app?
Apps are not compatible with b4xpage and its difficult to use adhelper library.


Its implemented by @Jack Cole in the Adshelper
 

cymilad

New Member
hi i error

Capture.PNG
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
 

SMOOTSARA

Active Member
Licensed User
Longtime User
This is a wrapper for Google Mobile Ads v20+ SDK.
It is a modified version of FirebaseAdmob (1).
This library works with Google Mobile Ads v20+. The previous library works with v19-.
Hi

I created a new program with B4A ver 11.5
I checked the "FirebaseAdMob2" library
I made the settings of the manifest editor ....
And I ran the program

At this line the program exits
B4X:
    BannerAd.LoadAd


Displays the following error
B4X:
Logger connected to: emulator-5554
--------- beginning of system
--------- beginning of crash
--------- beginning of main
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create, isFirst = true **
*** mainpage: B4XPage_Appear
** Activity (main) Resume **
After MobileAds_Ready
Consent: OBTAINED
Failed to load RewardedVideoAd: {
  "Code": 3,
  "Message": "No ad config.",
  "Domain": "com.google.android.gms.ads",
  "Cause": "null",
  "Response Info": {
    "Response ID": "null",
    "Mediation Adapter Class Name": "",
    "Adapter Responses": []
  }
}
Failed to load OpenAd: {
  "Code": 3,
  "Message": "No ad config.",
  "Domain": "com.google.android.gms.ads",
  "Cause": "null",
  "Response Info": {
    "Response ID": "null",
    "Mediation Adapter Class Name": "",
    "Adapter Responses": []
  }
}
Failed to load RewardedInterstitialAd: {
  "Code": 3,
  "Message": "No ad config.",
  "Domain": "com.google.android.gms.ads",
  "Cause": "null",
  "Response Info": {
    "Response ID": "null",
    "Mediation Adapter Class Name": "",
    "Adapter Responses": []
  }
}
java.lang.IncompatibleClassChangeError: The method 'java.lang.Class java.lang.Object.getClass()' was expected to be of type interface but instead was found to be of type virtual (declaration of 'com.google.android.gms.dynamic.ObjectWrapper' appears in /data/app/anywheresoftware.b4a.samples.smiley-2/base.apk)
    at com.google.android.gms.dynamic.ObjectWrapper.unwrap(com.google.android.gms:[email protected]@18.0.2:4)
    at com.google.android.gms.internal.ads.zzbji.zzl(com.google.android.gms:[email protected]@20.6.0:20)
    at com.google.android.gms.ads.BaseAdView.loadAd(com.google.android.gms:[email protected]@20.6.0:1)
    at anywheresoftware.b4a.admobwrapper.AdViewWrapper.LoadAd(AdViewWrapper.java:141)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.shell.Shell.runVoidMethod(Shell.java:777)
    at anywheresoftware.b4a.shell.Shell.raiseEventImpl(Shell.java:354)
    at anywheresoftware.b4a.shell.Shell.raiseEvent(Shell.java:255)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:144)
    at anywheresoftware.b4a.BA.raiseEvent(BA.java:193)
    at anywheresoftware.b4a.shell.DebugResumableSub$RemoteResumableSub.resume(DebugResumableSub.java:22)
    at anywheresoftware.b4a.BA.checkAndRunWaitForEvent(BA.java:267)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:137)
    at anywheresoftware.b4a.BA$1.run(BA.java:352)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6138)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
[IDE message - 10:41:02]
An error occurred.
Rapid Debugger failed to connect to process. Please try to run again.



This link can also be useful
https://stackoverflow.com/questions...cted-to-be-of-type-interface-but-was-found-to

and activity code :
B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
    
#End Region

'#BridgeLogger: True

Sub Process_Globals
    Public ActionBarHomeClicked As Boolean
End Sub

Sub Globals
    Private BannerAd As AdView
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Dim pm As B4XPagesManager
    pm.Initialize(Activity)
    
    
'    https://www.b4x.com/android/forum/threads/firebaseadmob2-google-mobile-ads-sdk-v20.129609/
    Dim m As MobileAds
    Wait For (m.Initialize) MobileAds_Ready
    m.SetConfiguration(m.CreateRequestConfigurationBuilder(Array("77A04EE40B2AFED2AFC67701365187EC"))) '
    
    Dim AdaptiveSize As Map = GetAdaptiveAdSize
    'Add Private BannerAd As AdView in Globals sub
    BannerAd.Initialize2("BannerAd", "ca-app-pub-3940256099942544/6300978111",AdaptiveSize.Get("native"))
    Activity.AddView(BannerAd, 0, 0,  AdaptiveSize.Get("width"), AdaptiveSize.Get("height"))
    BannerAd.LoadAd

End Sub


Sub GetAdaptiveAdSize As Map
    Dim ctxt As JavaObject
    ctxt.InitializeContext
    Dim AdSize As JavaObject
    Dim width As Int = 100%x / GetDeviceLayoutValues.Scale
    Dim Native As JavaObject = AdSize.InitializeStatic("com.google.android.gms.ads.AdSize").RunMethod("getCurrentOrientationAnchoredAdaptiveBannerAdSize", Array(ctxt, width))
    Return CreateMap("native": Native, "width": Native.RunMethod("getWidthInPixels", Array(ctxt)), _
        "height": Native.RunMethod("getHeightInPixels", Array(ctxt)))
End Sub

Sub Ad_ReceiveAd
    Log("Adview received")
End Sub

Sub Ad_FailedToReceiveAd (ErrorCode As String)
    Log("Failed: " & ErrorCode)
End Sub

Sub Ad_AdClosed
    Log("Closed")
End Sub

Sub Ad_AdOpened
    Log("Opened")
End Sub

'Template version: B4A-1.01
#Region Delegates

Sub Activity_ActionBarHomeClick
    ActionBarHomeClicked = True
    B4XPages.Delegate.Activity_ActionBarHomeClick
    ActionBarHomeClicked = False
End Sub

Sub Activity_KeyPress (KeyCode As Int) As Boolean
    Return B4XPages.Delegate.Activity_KeyPress(KeyCode)
End Sub

Sub Activity_Resume
    B4XPages.Delegate.Activity_Resume
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    B4XPages.Delegate.Activity_Pause
End Sub

Sub Activity_PermissionResult (Permission As String, Result As Boolean)
    B4XPages.Delegate.Activity_PermissionResult(Permission, Result)
End Sub

Sub Create_Menu (Menu As Object)
    B4XPages.Delegate.Create_Menu(Menu)
End Sub

#if Java
public boolean _onCreateOptionsMenu(android.view.Menu menu) {
     processBA.raiseEvent(null, "create_menu", menu);
     return true;
    
}
#End If
#End Region

'Program code should go into B4XMainPage and other pages.
 
Status
Not open for further replies.
Top