AdMob In Xamarin.Forms – 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. Before you start, you have to setup an Admob account.
  2. Once setup, press Get Started, and create a new App. You will receive an AdMob AppId, similar to this: ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX
  3. 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.

  1. Test Ads for Android
  2. Test Ads for iOS

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. Install the Xamarin.Firebase.Ads package from Nuget
  2. You may have to use a version lower than the latest, due to conflicts with the latest version of Xamarin.Forms.
  3. Before Xamarin.Forms.Init() in your MainActivity, add the following code
    Android.Gms.Ads.MobileAds.Initialize(ApplicationContext, "YOUR ANDROID APP ID HERE");
  4. 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
  5. 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" />
  6. 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. Install the Xamarin.Firebase.iOS.AdMob package from Nuget.
  2. Before Xamarin.Forms.Init() in your AppDelegate, add the following code.
    Google.MobileAds.MobileAds.Configure("YOUR IOS APP ID HERE");
  3. 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";

 


XAMARIN WEEKLY NEWSLETTER

Subscribe to a hand-picked round up of the best Xamarin development links every week. Published every Friday. Free.

Signup to Weekly Xamarin

* I do not maintain or run this newsletter, but I do recommend it.

Microsoft MVP | Xamarin MVP | Xamarin Forms Developer | Build Flutter

2 Comments

  1. Ryan Dixon

    Couldn’t we take this even further and just publish it as a nuget for us lazy folk ;D

    Great article as always!

    1. Adam Pedley

      Thanks.

      I don’t want to put it into a Nuget package, because that means I would have to support it. And I really don’t want to.

      Its 3 classes you have to copy and paste, its not that difficult 🙂