How to add Interstitial Ads in Xamarin.android ?

CastielTR 141 Reputation points
2021-08-10T14:35:43.053+00:00

I found a lot of source from Xamarin forms and Java source codes but I can't find in Xamarin.android. I need learn how to add the interstitial ads in xamarin.android. How to add the interstitial ads in xamarin.android (c#) ?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,294 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,571 Reputation points Microsoft Vendor
    2021-08-13T05:59:49.31+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!

    Sorry for the late response, I finally find this error(do not show the Interstitial Ads).

    Firstly, Google update them Interstitial ADmob 's API. So when we install the latest version(V 120.2.0) of Xamarin.GooglePlayServices.Ads, you will get a known issue(Name Clash in InterstitialAdLoadCallback and RewardedAdLoadCallback), it is still not fix this issue.

    However, we have strong community members, 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.

    122860-image.png

    122890-image.png

    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;  
           }  
    

    Here is running screenshot.

    123002-image.png

    Best Regards,

    Leon Lu


    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.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,571 Reputation points Microsoft Vendor
    2021-08-11T06:36:00.41+00:00

    Hello,​

    Welcome to our Microsoft Q&A platform!
    Firstly, please set up your app in your admob_account, create an AD type to Interstitial Ads. then Get the App ID and ad unit ID

    https://developers.google.com/admob/android/quick-start#set_up_your_app_in_your_admob_account

    122198-image.png

    You can install following NuGet package in your project.

       Xamarin.GooglePlayServices.Ads.Lite  
    

    Then add following tag in your layout. Add your UnitId to app:adUnitId

       <?xml version="1.0" encoding="utf-8"?>  
       <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
           xmlns:app="http://schemas.android.com/apk/res-auto"  
             
           xmlns:tools="http://schemas.android.com/tools"  
            
           android:layout_width="match_parent"  
           android:layout_height="match_parent">  
         
           <com.google.android.gms.ads.AdView  
               android:id="@+id/adView"  
               android:layout_width="match_parent"  
               android:layout_height="match_parent"  
               android:layout_centerHorizontal="true"  
               android:layout_alignParentBottom="true"  
               app:adSize="LEADERBOARD"  
               app:adUnitId="ca-app-pub-3940256099xxxxx544/1033173712" />  
       </RelativeLayout>  
    

    Add meta-data in the Application tag of AndroidManifest.xml, add your App ID to android:value.

       <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">  
       		<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-1215741977xxxxxx851~2383918044" />  
       	</application>  
       	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
       	<uses-permission android:name="android.permission.INTERNET" />  
    

    In the end, please add following code to your OnCreate method of MainActivity.cs.

       public class MainActivity : AppCompatActivity  
           {  
               protected override void OnCreate(Bundle savedInstanceState)  
               {  
                   base.OnCreate(savedInstanceState);  
                   Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
                   // Set our view from the "main" layout resource  
                   SetContentView(Resource.Layout.activity_main);  
         
                   MobileAds.Initialize(this,new MyADInit());  
               }  
               public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)  
               {  
                   Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
         
                   base.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
               }  
           }  
         
           internal class MyADInit : Java.Lang.Object, IOnInitializationCompleteListener  
           {  
               public void OnInitializationComplete(IInitializationStatus p0)  
               {  
                   // throw new System.NotImplementedException();  
                   var value = p0.AdapterStatusMap.Values;  
               }  
           }  
    

    Here is google article about the interstitial ad

    https://developers.google.com/admob/android/interstitial?hl=en-us

    xamarin.android provide a demo about it, you can refer to this thread:

    https://github.com/xamarin/GooglePlayServicesComponents/tree/main/samples/com.google.android.gms/play-services-ads-lite

    Best Regards,

    Leon Lu


    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.

    1 person found this answer helpful.

  2. Christopher Drosos 1 Reputation point
    2021-08-13T08:00:52.803+00:00

    Great code, really helpful but i would like to ask a question. Before this update we could show this kind of ad when we want with the .Show() command, now how we can do something like that? im not sure i understand how i can do it. how i control if a certain conditions are met then to show Interstitial ad?