
Google AdsMob with Xamarin Forms
Introduction :
Hi friends, I am a Software Developer to mobile cross-platform using Xamarin (C#). Xamarin is provided a native platform for mobile development and it’s very easy for learning c# developer.
Why we choose Xamarin :
Just Xamarin has been serviced and found that is 1+ million developers is doing this platform for mobile development.
Notability of the Xamarin:-
- Native Platform for every environment just Like Android, iOS, Windows Phone & Mac.
- Code Sharing with Xamarin Forms.
- Open Source.
- Performance close to Native.
- Full Hardware Supported.
- Simplified maintenance.
- Xamarin University provides smooth Onboarding.
AdMob with Xamarin (Android & iOS)
I have been recently experimenting with integrating ads into my applications as an experiment. just get it set up and working. I recently experimented with Google AdMob for my Cross Platform app “Social Post” and the results have been pretty good. I have faced a different type of doubt during Google AdMob integration.
I have followed this step during integration.
Step I.
So, the first thing that you will need to do is actually register for AdMob. This will give you two important pieces of information, your “Application Code” and your “Ad Unit Id”. We will use these later, but simply go to: https://apps.admob.com, register for a new app, link to an app in Firebase, and you will be off running.
Note: you must be added bank account details to Google AdMob when you will be done it then ads will appear on your app screen.
Step II.
Downloading Nuget Package:-
This one is a bit tricky since Xamarin. Forms require a very specific package to every platform.
For Android :

For iOS :

Step III.
Custom Control
For my app I am adding a custom data bindings or anything like that for the Ad Ids, so I just create a very-very simple custom control in my shared code:
using Xamarin.Forms;
namespace Blaffer
{
public class AAdMobView : Xamarin.Forms.View
{
public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(
nameof(AdUnitId),
typeof(string),
typeof(AAdMobView),
string.Empty);
public string AdUnitId
{
get => (string)GetValue(AdUnitIdProperty);
set => SetValue(AdUnitIdProperty, value);
}
}
}
Step IV.
Ad View Renderer for the Android :
Now, we have to go into our Android project and implement the custom control. Essentially just a method to create the native AdView and then set it when the page loads up.
using System.ComponentModel;
using Blaffer;
using Blaffr.Droid;
using Android.Content;
using Android.Gms.Ads;
using Android.Widget;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
using System;
[assembly: ExportRenderer(typeof(AAdMobView), typeof(AdMobViewRenderer))]
namespace Blaffr.Droid
{
public class AdMobViewRenderer : ViewRenderer<AAdMobView, AdView>
{
public AdMobViewRenderer(Context context) : base(context) { }
protected override void OnElementChanged(ElementChangedEventArgs<AAdMobView> e)
{
try
{
base.OnElementChanged(e);
//call first time for init view
if (e.NewElement != null && Control == null)
{
SetNativeControl(CreateAdView());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
try
{
base.OnElementPropertyChanged(sender, e);
//pass here AdUnitId if exists
if (e.PropertyName == nameof(AdView.AdUnitId))
Control.AdUnitId = Element.AdUnitId;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private AdView CreateAdView()
{
try
{
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;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return null;
}
}
}
Update MainActivity :
Go into your Main Activity and initialize your MobileAds from the SDK:
MobileAds.Initialize(ApplicationContext, “pass here your Android app_id form AdsMob”);
Update Manifest:
You will now need to add 2 permissions:
<uses-permission android:name=”android.permission.INTERNET” />
<uses-permission android:name=”android.permission.ACCESS_NETWORK_STATE” />
Ad View Renderer for the iOS :
Now, we have to go into our iOS project and implement the custom control. Essentially just a method to create the native AdView and then set it when the page loads up.
using AdSupport;
using Blaffer;
using Blaffer.iOS.Renderer;
using CoreGraphics;
using Google.MobileAds;
using System;
using System.ComponentModel;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(AAdMobView), typeof(AdMobViewRenderer))]
namespace Blaffer.iOS.Renderer
{
public class AdMobViewRenderer : ViewRenderer<AAdMobView, BannerView>
{
BannerView adView;
bool viewOnScreen;
protected override void OnElementChanged(ElementChangedEventArgs<AAdMobView> e)
{
base.OnElementChanged(e);
if (e.NewElement == null)
return;
if (e.OldElement == null)
{
//if your app privacy →Advertising →Limit Ad Tracking is ensure that is disable.
if (ASIdentifierManager.SharedManager.IsAdvertisingTrackingEnabled)
{
}
//here add adUnitID
adView = new BannerView(AdSizeCons.Banner, new CGPoint(0, 0))
{
AdUnitID = Element.AdUnitId,
RootViewController = GetRootViewController()
};
//if change you adsize like mobile orientation landscape/portrait
adView.WillChangeAdSizeTo += (sender, args) =>
{
};
//when application will be leave
adView.WillLeaveApplication += (sender, args) =>
{
};
//when screen dismissed
adView.ScreenDismissed += (sender, args) =>
{
};
//when screen will apear
adView.WillPresentScreen += (sender, args) =>
{
};
//call when ads received from google ads
adView.AdReceived += (sender, args) =>
{
viewOnScreen = true;
if (!viewOnScreen) this.AddSubview(adView);
};
var request = Request.GetDefaultRequest();
//e.NewElement.HeightRequest = GetSmartBannerDpHeight();
adView.LoadRequest(request);
adView.ReceiveAdFailed += (object sender, BannerViewErrorEventArgs ea) => {
viewOnScreen = false;
Console.WriteLine(string.Format(“Code ‘{0}’, : Domain ‘{1}’, : error desp ‘{2}’ “, ea.Error.Code,ea.Error.Domain,ea.Error.Description));
//Console.WriteLine(string.Format(ea.Error.Code + ea.Error.Domain + ea.Error.Description));
adView.LoadRequest(request);
};
base.SetNativeControl(adView);
}
}
private UIViewController GetRootViewController()
{
foreach (UIWindow window in UIApplication.SharedApplication.Windows)
{
if (window.RootViewController != null)
{
return window.RootViewController;
}
}
return null;
}
private int GetSmartBannerDpHeight()
{
var dpHeight = (double)UIScreen.MainScreen.Bounds.Height;
if (dpHeight <= 400) return 32;
if (dpHeight > 400 && dpHeight <= 720) return 50;
return 90;
}
}
}
Note : In the iOS device please should be ensure that is your app privacy →Advertising →Limit Ad Tracking is disabled otherwise google would not be able for ads serving.
Update AppDelegate :
MobileAds.Configure(“pass here you iOS app_id form AdsMob”);
Update infor.plist :
You will now need to add its some permission:
adds permission to infor.plist file

Step V :
Update Xaml :
Now we can add the custom control to the bottom of your XAML.
First add your custom xmlns name space:
xmlns:local=”clr-namespace:Blaffer.Controls;assembly=Blaffer”
Then add in the custom control and boom done!
<ContentView.Content>
<local:AAdMobView AdUnitId=”{Binding AdUnitId}” BackgroundColor=”Transparent” />
</ContentView.Content>
Update .cs class:
public AdsContentView()
{
InitializeComponent();
BindingContext = new AdsViewModel();
}
Update ViewModel :
public AdsViewModel()
{
if (Device.RuntimePlatform == Device.iOS)
AdUnitId = “pass here iOS UDID”;
else if (Device.RuntimePlatform == Device.Android)
AdUnitId = “pass here Android UDID”;
}
Success!
You should now be able to run your app and boom! Test Ad!

Important
- A few things to know, since we are using a Smart Banner you can not have any padding around the adview it must fill the entire screen.
- You will see a test banner on the screen. If you don’t set the background color to red or something like this and if it isn’t rendering look at the output as it may not be able to connect or you have some padding.
- If you need padding then set it to just “Banner”.
you can see sample code from the GitHub: https://github.com/sharmapranav/Xamarin
Thanks for your attention :).
