Display Google Ads In Your Mobile App

AdMob is a company that provided the ability to display ads in your mobile app. It is now a part of Google, and hence you may hear it referred as Firebase Ads or Google Mobile Ads. You can use this on iOS or Android. No other platform is currently supported at the time of this post.

I have working sample code in my AdMob Github Repo.

Setup Account

  1. Once setup, press Get Started, and create a new App. You will receive an AdMob AppId, similar to this: ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX
  2. You will need to create one for Android and one for iOS

Keep these handy, you will need them soon.

Create Ad Unit

Next you need to create an Ad Unit. The most common, would be a Banner.

If you create your own, they do take some time to come through, and you will notice when trying to view your ad unit, you will get this error message.

There was a problem getting an ad response. ErrorCode: 0 Failed to load ad:0

Hence you can use test ones initially, while getting your layout right.

You will get an Id like this, that is different for both iOS and Android.

ca-app-pub-3940256099942544/2934735716

Xamarin.Forms View

The implementation of AdView is different on each platform, but we need a common control to use in Xamarin.Forms. Create a new class as below. We have an AdUnitId as we will need to pass that through to the AdView control.

public class AdMobView : View
{
    public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(
				   nameof(AdUnitId),
				   typeof(string),
				   typeof(AdMobView),
				   string.Empty);

    public string AdUnitId
    {
	get => (string)GetValue(AdUnitIdProperty);
	set => SetValue(AdUnitIdProperty, value);
    }
}

Android

  1. You may have to use a version lower than the latest, due to conflicts with the latest version of Xamarin.Forms.
  2. Before Xamarin.Forms.Init() in your MainActivity, add the following code
    Android.Gms.Ads.MobileAds.Initialize(ApplicationContext, "YOUR ANDROID APP ID HERE");
  3. Make sure you add the following permissions to your Android project.
    Go to the properties of your Android project, then Android Manifest, then select the required permissions.
    ACCESS_NETWORK_STATE
    INTERNET
  4. Now go to your AndroidManifest.xml (expand the Properties item) and add the following activity, in between the <manifest> tags.
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
  5. Finally we need to add the CustomRenderer. Create a new class in your Android project, and create the following renderer.
    [assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
    namespace Admob.Droid
    {
    	public class AdMobViewRenderer : ViewRenderer<AdMobView, AdView>
    	{
    		public AdMobViewRenderer(Context context) : base(context) { }
    		
    		protected override void OnElementChanged(ElementChangedEventArgs e)
    		{
    			base.OnElementChanged(e);
    
    			if (e.NewElement != null && Control == null)
    				SetNativeControl(CreateAdView());			
    		}
    
    		protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    		{
    			base.OnElementPropertyChanged(sender, e);
    
    			if (e.PropertyName == nameof(AdView.AdUnitId))
    				Control.AdUnitId = Element.AdUnitId;
    		}
    
    		private AdView CreateAdView()
    		{			
    			var adView = new AdView(Context)
    			{
    				AdSize = AdSize.SmartBanner,
    				AdUnitId = Element.AdUnitId
    			};
    			
    			adView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent); 
    
    			adView.LoadAd(new AdRequest.Builder().Build());
    		
    			return adView;
    		}
    	}
    }

iOS

  1. Before Xamarin.Forms.Init() in your AppDelegate, add the following code.
    Google.MobileAds.MobileAds.Configure("YOUR IOS APP ID HERE");
  2. Now add the following renderer in your iOS project.
    [assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
    namespace Admob.iOS
    {
    	public class AdMobViewRenderer : ViewRenderer<AdMobView, BannerView>
    	{
    		protected override void OnElementChanged(ElementChangedEventArgs e)
    		{
    			base.OnElementChanged(e);
    			if (Control == null)
    			{
    				SetNativeControl(CreateBannerView());				
    			}
    		}
    		
    		protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
    		{
    			base.OnElementPropertyChanged(sender, e);
    
    			if (e.PropertyName == nameof(BannerView.AdUnitID))
    				Control.AdUnitID = Element.AdUnitId;
    		}
    
    		private BannerView CreateBannerView()
    		{
    			var bannerView = new BannerView(AdSizeCons.SmartBannerPortrait)
    			{
    				AdUnitID = Element.AdUnitId,
    				RootViewController = GetVisibleViewController()
    			};
    
    			bannerView.LoadRequest(GetRequest());
    
    			Request GetRequest()
    			{
    				var request = Request.GetDefaultRequest();
    				return request;
    			}
    			
    			return bannerView;
    		}
    			
    		private UIViewController GetVisibleViewController()
    		{
    			var windows = UIApplication.SharedApplication.Windows;
    			foreach (var window in windows)
    			{
    				if (window.RootViewController != null)
    				{
    					return window.RootViewController;
    				}				
    			}
    			return null;
    		}
    	}
    }
    

Xamarin.Forms

Now we want to view it on Xamarin.Forms. You can add the banner to your app, by adding the control to your page, as per below.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Admob"
             x:Class="Admob.MainPage">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <Label Text="Welcome to Xamarin Forms!"
               VerticalOptions="Center"
               HorizontalOptions="Center" />

        <local:AdMobView AdUnitId="{Binding AdUnitId}" Grid.Row="1" />
    </Grid>
</ContentPage>

You will want to change the AdUnitId, depending upon which platform you are on. You can use a simple if statement and retrieve the appropriate key.

if (Device.RuntimePlatform == Device.iOS)
    AdUnitId = "iOS Key";
else if (Device.RuntimePlatform == Device.Android)
    AdUnitId = "Android Key";

Adam Pedley

Microsoft MVP | Xamarin MVP | Xamarin Certified Developer | Xamarin Forms Developer | Melbourne, Australia