Admob with Xamarin Android Part 1: BannerAd
This will be a brief overview on how to get admob working with Xamarin.
I highly suggest you run this on a real phone. I’m not sure if the virtual phones can load content on the internet. I always develop on a real phone.
Sample code located in a repo at github
Create an admob account
First you will need to create an account. After you do so create an ad, you must choose either full page aka Interstitial, or banner ad.
Install Play Services Component
This is quite simple right click on the components folder (in visual studio, or xamarin studio) and click get more components.
Find the play services you require and click Add to App.
Add the following XML to your Android Manifest file, place it in between the
Add proper permissions
You need to add these permissions to your AssemblyInfo.cs
The standard code to create an ad is something like this:
Doing things better
However in the interests of showing, and creating more flexible code this tutorial will guide you through the wrapper implementation I constructed, and posted on github.
To start I created admobDemo.AndroidPhone.ad.AdWrapper.cs This code abstracts out some of the verbose building process, and allows the building Ad code to be reused. the code pertaining banner ads looks like this
The ConstructStandardBanner method takes in a context (usually this in an activity class), an ad size which usually people use AdSize.SmartBanner, and the unitID of your Ad (ID that you got from admob).
The extension method
CustomBuild allows you to define things in the requestbuilder (which I have not changed in this implementation). The request builder is mostly to give demographic information to Google, to help serve up a better ad.
Your main activity should end up looking something like this:
As you can see we are constructing the banner using our wrapper. Then we are calling it’s custom build extension method. We are getting a LinearLayout that has been defined in the views’s .axml file (you can add your own their if you wish) and then we are injecting the banner into this LinearLayout.
You need to make sure you pause and resume the bannerAds by including them in the overrides on the Activity class. You also need to make sure you give it your ad ID.
If you have issues where the ad does not show, you may want to make sure whatever LinearLayout (or other UI control) you inject the banner into is being shown in the UI. I once saw a problem where one layout was filling the parent so the other was not being shown, therefore the banner was hidden.