Hello,
Welcome to our Microsoft Q&A platform!
I'm afraid it is still a not fix issue of Xamarin.GooglePlayServices.Ads
.
Here is a workaroud to fix this issue in the end of the page.
Step 1. we need to create a new InterstitialCallback
, If we use official InterstitialAdLoadCallback
, we cannot override the OnAdLoaded
method, because InterstitialAdLoadCallback
forget to achieve the OnAdLoaded
method from the AdLoadCallback
, you can see the following screenshot. InterstitialAdLoadCallback
do not have the OnAdLoaded
method, it is unbelievable.
Let's start our code to fix it. Create a new InterstitialCallback.cs
.
public abstract class InterstitialCallback : Android.Gms.Ads.Interstitial.InterstitialAdLoadCallback
{
[Register("onAdLoaded", "(Lcom/google/android/gms/ads/interstitial/InterstitialAd;)V", "GetOnAdLoadedHandler")]
public virtual void OnAdLoaded(Android.Gms.Ads.Interstitial.InterstitialAd interstitialAd)
{
}
private static Delegate cb_onAdLoaded;
private static Delegate GetOnAdLoadedHandler()
{
if (cb_onAdLoaded is null)
cb_onAdLoaded = JNINativeWrapper.CreateDelegate((Action<IntPtr, IntPtr, IntPtr>)n_onAdLoaded);
return cb_onAdLoaded;
}
private static void n_onAdLoaded(IntPtr jnienv, IntPtr native__this, IntPtr native_p0)
{
InterstitialCallback thisobject = GetObject<InterstitialCallback>(jnienv, native__this, JniHandleOwnership.DoNotTransfer);
Android.Gms.Ads.Interstitial.InterstitialAd resultobject = GetObject<Android.Gms.Ads.Interstitial.InterstitialAd>(native_p0, JniHandleOwnership.DoNotTransfer);
thisobject.OnAdLoaded(resultobject);
}
}
Then back to the OnCreate
method of MainActivity.cs
. Using following code to load the InterstitialAd
Android.Gms.Ads.Interstitial.InterstitialAd.Load(this, "ca-app-pub-1215741977455851/6629466575", new AdRequest.Builder().Build(), new InterstitialCallbackinherit());
In the end, please create a InterstitialCallbackinherit.cs
to extend the InterstitialCallback
,
public class InterstitialCallbackinherit : InterstitialCallback
{
public override void OnAdLoaded(Android.Gms.Ads.Interstitial.InterstitialAd interstitialAd)
{
MainActivity.interstitialAd = interstitialAd;
interstitialAd.Show(MainActivity.instance);
base.OnAdLoaded(interstitialAd);
}
public override void OnAdFailedToLoad(LoadAdError p0)
{
base.OnAdFailedToLoad(p0);
}
}
MainActivity.instance
is a public static MainActivity instance
in the MainActivity.cs
public class MainActivity : AppCompatActivity
{
public static MainActivity instance;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
instance = this;
}
Best Regards,
Wenyan Zhang
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.