Google AdMob - Display Ads In Xamarin Forms

Introduction

Hello everyone, I am going to show how to display Google AdMob Ads for Android and iOS applications for CSharp - Xamarin Mobile Development.

A banner Ad is like a ribbon. This is selected if our requirement is to provide an ad at the footer or at header part, this does not cover the entire region of the Page. It only uses a portion of the app page.

Interstitial Ads cover the entire page with the ad, so mostly this is displayed as a popup. This process is the same for displaying rewarded type ads.

Requirements

We need “App Id” and “Unit Id”, which are created in “AdMob by Google” available on this website,

  • https://code.msdn.microsoft.com/Google-AdMob-in-Xamarinform-cd500224/https://www.google.com/admob/.

To create these follow the tutorial available here:

  • @https://code.msdn.microsoft.com/Google-AdMob-in-Xamarinform-cd500224/https://code.msdn.microsoft.com/Google-AdMob-in-Xamarinform-cd500224/
  • Or @http://allsoftwaredevelopments.blogspot.com/2018/09/google-admob-mobile-development_4.html
  • Or @https://www.c-sharpcorner.com/article/getting-started-with-google-admob/

Steps in Brief,

  • Adding required packages.
  • Changes to be done in Manifest.xml file(only for Android)
  • Creating Custom Renders to access Ads for Banner type Ads.
  • Accessing Custom Renders in the code to display Banner type Ads.
  • Creating Dependency Services to access Ads for Interstitial type Ads.
  • Accessing Dependency Services in the code to display Interstitial type Ads.

Steps in Detail,

Adding required packages

Here, we are using Custom Renders so the packages are to be added in Xamarin.Android and Xamarin.iOS folders only. There is no need to add any package in PCL folder.

  1. For Android
    Add “Xamarin.GooglePlayServices.Ads” package.

  2. For iOS
    Add “Xamarin.Firebase.iOS.AdMob” Package

Changes to be done in Manifest.xml file (only for Android)

Add Permissions for "INTERNET" and "ACCESS_NETWORK_STATE" and then add the following lines in the Manifest.xml file in Project->Android->Properties folder.

XML

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.AdMob">  
  3.     <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" />  
  4.     <uses-permission android:name="android.permission.INTERNET" />  
  5.     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  6.     <application android:label="AdMob.Android">  
  7.         <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />  
  8.     </application>  
  9. </manifest>  

Creating Custom Renders to access Banner type Ads

  1. In PCL,
    While showing the Banner ad we have to set the size also. For this purpose we have to use custom renders as we can add nuget packages for AdMob by Google in native folders only.

Different sizes of banners available are,

Size in dp (WxH)DescriptionAvailabilityAdSize constant
320x50Standard BannerPhones and TabletsBANNER
320x100Large BannerPhones and TabletsLARGE_BANNER
300x250IAB Medium RectanglePhones and TabletsMEDIUM_RECTANGLE
468x60IAB Full-Size BannerTabletsFULL_BANNER
728x90IAB LeaderboardTabletsLEADERBOARD
Screen width x 32|50|90Smart BannerPhones and TabletsSMART_BANNER

Now in PCL add the following class with name AdBanner.cs

C#

  1. using System;  
  2. using Xamarin.Forms;  
  3.   
  4. namespace AdMob.CustomRenders  
  5. {  
  6.     public class AdBanner : View  
  7.     {  
  8.         public enum Sizes { Standardbanner, LargeBanner, MediumRectangle, FullBanner, Leaderboard, SmartBannerPortrait }  
  9.         public Sizes Size { get; set; }  
  10.         public AdBanner()  
  11.         {  
  12.             this.BackgroundColor = Color.Accent;  
  13.         }  
  14.     }  
  15. }  
  1. In Android.
    In Android we have to add the following class to create a view and use it in PCL with CustomRenders concept, let us create it here with name AdBanner_Droid.cs

    C#
    1. using System;  
    2. using AdMob;  
    3. using Android.Gms.Ads;  
    4. using Xamarin.Forms;  
    5. using Xamarin.Forms.Platform.Android;  
    6. using AdMob.CustomRenders;  
    7. using AdMob.Droid.CustomRenders;  
    8. using Android.Content;  
    9.   
    10. [assembly: ExportRenderer(typeof(AdBanner), typeof(AdBanner_Droid))]  
    11. namespace AdMob.Droid.CustomRenders  
    12. {  
    13.     public class AdBanner_Droid : ViewRenderer  
    14.     {  
    15.         Context context;  
    16.         public AdBanner_Droid(Context _context) : base(_context)  
    17.         {  
    18.             context = _context;  
    19.         }  
    20.         protected override void OnElementChanged(ElementChangedEventArgs<View> e)  
    21.         {  
    22.             base.OnElementChanged(e);  
    23.             if (e.OldElement == null)  
    24.             {  
    25.                 var adView = new AdView(Context);  
    26.                 switch ((Element as AdBanner).Size)  
    27.                 {  
    28.                     case AdBanner.Sizes.Standardbanner:  
    29.                         adView.AdSize = AdSize.Banner;  
    30.                         break;  
    31.                     case AdBanner.Sizes.LargeBanner:  
    32.                         adView.AdSize = AdSize.LargeBanner;  
    33.                         break;  
    34.                     case AdBanner.Sizes.MediumRectangle:  
    35.                         adView.AdSize = AdSize.MediumRectangle;  
    36.                         break;  
    37.                     case AdBanner.Sizes.FullBanner:  
    38.                         adView.AdSize = AdSize.FullBanner;  
    39.                         break;  
    40.                     case AdBanner.Sizes.Leaderboard:  
    41.                         adView.AdSize = AdSize.Leaderboard;  
    42.                         break;  
    43.                     case AdBanner.Sizes.SmartBannerPortrait:  
    44.                         adView.AdSize = AdSize.SmartBanner;  
    45.                         break;  
    46.                     default:  
    47.                         adView.AdSize = AdSize.Banner;  
    48.                         break;  
    49.                 }  
    50.                 // TODO: change this id to your admob id  
    51.                 adView.AdUnitId = "Your AdMob id";  
    52.                 var requestbuilder = new AdRequest.Builder();  
    53.                 adView.LoadAd(requestbuilder.Build());  
    54.                 SetNativeControl(adView);  
    55.             }  
    56.         }  
    57.     }  
    58. }  
    At this line adView.AdUnitId = "Your Ad Unit id";

    We have to place our AdMob Banner unit id.
  1. In iOS,
    In iOS we have to add the following class to create a view and use it in PCL with CustomRenders concept, let us create it here with name AdBanner_iOS.cs

    C#
    1. using System;  
    2. using AdMob.CustomRenders;  
    3. using AdMob.iOS.CustomRenders;  
    4. using CoreGraphics;  
    5. using Google.MobileAds;  
    6. using UIKit;  
    7. using Xamarin.Forms;  
    8. using Xamarin.Forms.Platform.iOS;  
    9. //using GoogleAdMobAds;  
    10.   
    11.   
    12.   
    13. [assembly: ExportRenderer(typeof(AdBanner), typeof(AdBanner_iOS))]  
    14. namespace AdMob.iOS.CustomRenders  
    15. {  
    16.     public class AdBanner_iOS : ViewRenderer  
    17.     {  
    18.         protected override void OnElementChanged(ElementChangedEventArgs<View> e)  
    19.         {  
    20.             base.OnElementChanged(e);  
    21.   
    22.             if (e.OldElement == null)  
    23.             {  
    24.                 BannerView bannerView = null;  
    25.   
    26.                 switch ((Element as AdBanner).Size)  
    27.                 {  
    28.                     case AdBanner.Sizes.Standardbanner:  
    29.                         bannerView = new BannerView(AdSizeCons.Banner, new CGPoint(0, 0));  
    30.                         break;  
    31.                     case AdBanner.Sizes.LargeBanner:  
    32.                         bannerView = new BannerView(AdSizeCons.LargeBanner, new CGPoint(0, 0));  
    33.                         break;  
    34.                     case AdBanner.Sizes.MediumRectangle:  
    35.                         bannerView = new BannerView(AdSizeCons.MediumRectangle, new CGPoint(0, 0));  
    36.                         break;  
    37.                     case AdBanner.Sizes.FullBanner:  
    38.                         bannerView = new BannerView(AdSizeCons.FullBanner, new CGPoint(0, 0));  
    39.                         break;  
    40.                     case AdBanner.Sizes.Leaderboard:  
    41.                         bannerView = new BannerView(AdSizeCons.Leaderboard, new CGPoint(0, 0));  
    42.                         break;  
    43.                     case AdBanner.Sizes.SmartBannerPortrait:  
    44.                         bannerView = new BannerView(AdSizeCons.SmartBannerPortrait, new CGPoint(0, 0));  
    45.                         break;  
    46.                     default:  
    47.                         bannerView = new BannerView(AdSizeCons.Banner, new CGPoint(0, 0));  
    48.                         break;  
    49.                 }  
    50.   
    51.                 // TODO: change this id to your admob id  
    52.                 bannerView.AdUnitID = "Your AdMob Banner Ad Unit id";  
    53.                 foreach (UIWindow uiWindow in UIApplication.SharedApplication.Windows)  
    54.                 {  
    55.                     if (uiWindow.RootViewController != null)  
    56.                     {  
    57.                         bannerView.RootViewController = uiWindow.RootViewController;  
    58.                     }  
    59.                 }  
    60.                 var request = Request.GetDefaultRequest();  
    61.                 bannerView.LoadRequest(request);  
    62.                 SetNativeControl(bannerView);  
    63.             }  
    64.   
    65.         }  
    66.   
    67.     }  
    68. }  
    At this line adView.AdUnitId = "Your Ad Unit id";

    We have to place our AdMob Banner unit id.

Accessing Custom Renders to Display Banner Type Ads

Now, the only task remaining in our current tutorial is using the created custom renders in our code.

UI design code in XAML, for examlple in BannerAdPage.xaml

Here, we have to create a local object as in the following code and call the custom render as <local:AdBanner />

XAML

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentPage   
  3.     xmlns="http://xamarin.com/schemas/2014/forms"   
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"   
  5.     xmlns:local="clr-namespace:AdMob.CustomRenders;assembly=AdMob"  
  6.     x:Class="AdMob.Views.BannerAdPage">  
  7.   
  8.     <ContentPage.Padding>  
  9.         <OnPlatform x:TypeArguments="Thickness">  
  10.             <On Platform="iOS" Value="0,20,0,0"/>  
  11.             <On Platform="Android" Value="0,0,0,0"/>  
  12.             <On Platform="WinPhone" Value="0,0,0,0"/>  
  13.         </OnPlatform>  
  14.     </ContentPage.Padding>  
  15.       
  16.     <ContentPage.Content>  
  17.         <StackLayout x:Name="stackLayout" BackgroundColor="Yellow" VerticalOptions="FillAndExpand" Padding="0,0,0,0">  
  18.             <Label Text="Banner Advertisement" HorizontalOptions="CenterAndExpand" TextColor="Green" FontSize="25" />  
  19.             <local:AdBanner Size="Standardbanner" VerticalOptions="EndAndExpand"/>  
  20.         </StackLayout>  
  21.     </ContentPage.Content>  
  22.       
  23. </ContentPage> 

The Banner type ad is displayed at the bottom of the page, and this can be placed anywhere in the page. For this tutorial I have placed it at the lower/footer part of the page.

Creating Dependency Services to access Interstitial type Ads

  1. In PCL
    Unlike Banner Ads, Interstitial Ads have only one kind of size; i.e., the full page of the application. We can show a popup to display our ad, but the popup is not created by us. It is done by the installed SDK itself. We only have to call the popup to appear when required, suppose on a button click here.

    Now in PCL add the following Interface, for example, assume name IAdInterstitial.cs

    C#
    1. using System;  
    2. namespace AdMob.DependencyServices  
    3. {  
    4.     public interface IAdInterstitial  
    5.     {  
    6.         void ShowAd();  
    7.     }  
    8. }  
  1. In Android
    In Android add the following class , Assume AdInterstitial_Droid.cs

    C#
    1. using System;  
    2. using AdMob.DependencyServices;  
    3. using AdMob.Droid.DependencyServices;  
    4. using Android.Gms.Ads;  
    5. using Xamarin.Forms;  
    6.   
    7. [assembly: Dependency(typeof(AdInterstitial_Droid))]  
    8. namespace AdMob.Droid.DependencyServices  
    9. {  
    10.     public class AdInterstitial_Droid : IAdInterstitial  
    11.     {  
    12.         InterstitialAd interstitialAd;  
    13.   
    14.         public AdInterstitial_Droid()  
    15.         {  
    16.             interstitialAd = new InterstitialAd(Android.App.Application.Context);  
    17.   
    18.             // TODO: change this id to your admob id  
    19.             interstitialAd.AdUnitId = "Your AdMob id";  
    20.             LoadAd();  
    21.         }  
    22.   
    23.         void LoadAd()  
    24.         {  
    25.             var requestbuilder = new AdRequest.Builder();  
    26.             interstitialAd.LoadAd(requestbuilder.Build());  
    27.         }  
    28.   
    29.         public void ShowAd()  
    30.         {  
    31.             if (interstitialAd.IsLoaded)  
    32.                 interstitialAd.Show();  
    33.   
    34.             LoadAd();  
    35.         }  
    36.     }  
    37. }  
    At this line adView.AdUnitId = "Your Interstitial AdMob Unit id";

    We have to place our Your Interstitial AdMob Unit id.
  1. In iOS
    In iOS add the following class, Assume AdInterstitial_iOS.cs

    C#  
    1. using System;    
    2. using AdMob.DependencyServices;    
    3. using AdMob.iOS.DependencyServices;    
    4. using Google.MobileAds;    
    5. using UIKit;    
    6. using Xamarin.Forms;    
    7.     
    8. [assembly: Dependency(typeof(AdInterstitial_iOS))]    
    9. namespace AdMob.iOS.DependencyServices    
    10. {    
    11.     public class AdInterstitial_iOS : IAdInterstitial    
    12.    {    
    13.        Interstitial interstitial;    
    14.     
    15.         public AdInterstitial_iOS()    
    16.         {    
    17.             LoadAd();    
    18.             interstitial.ScreenDismissed += (s, e) => LoadAd();    
    19.         }    
    20.     
    21.         void LoadAd()    
    22.         {    
    23.             // TODO: change this id to your admob id    
    24.             interstitial = new Interstitial("Your AdMob Interstitial Ad Unit id");    
    25.     
    26.             var request = Request.GetDefaultRequest();    
    27.             request.TestDevices = new string[] {"Your Test Device ID""GADSimulator" };    
    28.             interstitial.LoadRequest(request);    
    29.         }    
    30.     
    31.         public void ShowAd()    
    32.         {    
    33.             if (interstitial.IsReady)    
    34.             {    
    35.                 var viewController = GetVisibleViewController();    
    36.                 interstitial.PresentFromRootViewController(viewController);    
    37.             }    
    38.         }    
    39.         UIViewController GetVisibleViewController()    
    40.         {    
    41.             var rootController = UIApplication.SharedApplication.KeyWindow.RootViewController;    
    42.     
    43.             if (rootController.PresentedViewController == null)    
    44.                 return rootController;    
    45.     
    46.             if (rootController.PresentedViewController is UINavigationController)    
    47.             {    
    48.                 return ((UINavigationController)rootController.PresentedViewController).VisibleViewController;    
    49.             }    
    50.     
    51.             if (rootController.PresentedViewController is UITabBarController)    
    52.             {    
    53.                 return ((UITabBarController)rootController.PresentedViewController).SelectedViewController;    
    54.             }    
    55.     
    56.             return rootController.PresentedViewController;    
    57.         }    
    58.     }    
    59. }  
    At this line adView.AdUnitId = "Your Interstitial AdMob Unit id";

    We have to place our Your Interstitial AdMob Unit id.

Note
To generate Interstitial Ad in iOS for testing purposes we have to add the following line with an array of test device ID's or else you won't get an ad to display.

  1. request.TestDevices = new string[] {"Your Test Device ID""GADSimulator" };  

For either simulator or for the physical device to test in debug mode we have to submit the device ID, and the above-presented line is to be removed while submitting the app in release mode.

To get the Device Id

  1. First, fill the entire code using the empty string for device Id.
  2. Allow it to run.
  3. Now click the button to open Interstitial Ad.
  4. Then Observe the Application Output console of IDE for the following line

    "<Google> To get test ads on this device, call: request.testDevices = @[ @"07*******************************89" ];"

  5. "07*******************************89" this will be your device Id. Copy this.
  6. Instead of empty string now paste the above Id and now run the program.
    For Simulators the device Id need not be a number/numeric value It can also be a text like "IGADSimulator" or "GAD_SIMULATOR_ID" or "Simulator" or ...

Accessing Dependency Services to Display Interstitial type Ads :

UI design code in XAML, for example, in "BannerAdPage.xaml and we have to open the Interstitial Ad on button Click. So the button click event is handled in the backed page of the UI created for example in "BannerAdPage.xaml.cs".

In BannerAdPage.xaml

XAML

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="AdMob.Views.InterstitialAdPage">  
  3.   
  4.     <ContentPage.Padding>  
  5.         <OnPlatform x:TypeArguments="Thickness">  
  6.             <On Platform="iOS" Value="0,20,0,0"/>  
  7.             <On Platform="Android" Value="0,0,0,0"/>  
  8.             <On Platform="WinPhone" Value="0,0,0,0"/>  
  9.         </OnPlatform>  
  10.     </ContentPage.Padding>  
  11.       
  12.     <ContentPage.Content>  
  13.         <StackLayout x:Name="stackLayout" VerticalOptions="FillAndExpand" Padding="0,0,0,0">  
  14.             <Label Text="Interstitial Advertisements" HorizontalOptions="CenterAndExpand" FontSize="30" TextColor="White" />  
  15.             <StackLayout VerticalOptions="CenterAndExpand" Padding="40,0,40,0">  
  16.                 <Button Text="Interstitial" HorizontalOptions="FillAndExpand" TextColor="Blue"  BackgroundColor="White" Clicked="InterstitialAdShowClick"/>  
  17.             </StackLayout>  
  18.         </StackLayout>  
  19.     </ContentPage.Content>  
  20. </ContentPage>  

In BannerAdPage.xaml.cs

C#

  1. using System;  
  2. using System.Collections.Generic;  
  3. using AdMob.DependencyServices;  
  4. using Xamarin.Forms;  
  5.   
  6. namespace AdMob.Views  
  7. {  
  8.     public partial class InterstitialAdPage : ContentPage  
  9.     {  
  10.         public InterstitialAdPage()  
  11.         {  
  12.             InitializeComponent();  
  13.         }  
  14.   
  15.         void InterstitialAdShowClick(object sender, EventArgs e)  
  16.         {  
  17.             DependencyService.Get<IAdInterstitial>().ShowAd();  
  18.         }  
  19.     }  
  20. }  

To open the Interstitial Ad you have to click the button.

Result - Banner Type Ad

Banner Type Ad

Interstitial Type Ad

Interstitial Type Ad

Interstitial Type Ad

Conclusion

This is how to create an ad in Xamarin.Forms using AdMob by Google.

References

  • To download the current tutorial sample please visit,

    https://code.msdn.microsoft.com/Google-AdMob-in-Xamarinform-cd500224/

  • For more knowledge about Banner Ads visit the following links,

    https://code.msdn.microsoft.com/Google-AdMob-in-Xamarinform-cd500224/
    https://developers.google.com/admob/android/banner?hl=en-GB.

  • For more knowledge about Interstitial ads visit the following links,

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

  • To learn how to create API keys for your application in AdMob by Google visit,

    https://code.msdn.microsoft.com/Google-AdMob-in-Xamarinform-cd500224/
    Or http://allsoftwaredevelopments.blogspot.com/2018/09/google-admob-mobile-development_4.html
    Or https://www.c-sharpcorner.com/article/getting-started-with-google-admob/

  • To learn about more Xamarin tutorials please visit,

    https://xamarindevelopers.blogspot.com/.
    Or
    https://code.msdn.microsoft.com/Google-AdMob-in-Xamarinform-cd500224/
    https://www.c-sharpcorner.com/members/pvspreddy/articles.

  • To learn about other technologies/tutorials please visit,

    https://code.msdn.microsoft.com/Google-AdMob-in-Xamarinform-cd500224/
    https://allsoftwaredevelopments.blogspot.com/