Admob for Xamarin made easy

Home / Admob for Xamarin made easy

Admob for Xamarin made easy

May 6, 2019 | Guide, Plugin, Tutorial | 23 Comments

In this tutorial I’ll show you how to monetize your Xamarin apps with AdMob using my MTAdmob plugin.

UPDATE: I’ve added on github the source code of a project to test this Admob plugin. You can find it here: https://github.com/marcojak/TestMTAdmob

To help you to speed up your Xamarin development, I’ve created a set of plugins, one of them is MTAdmob. Thanks to this plugin you can add Admob banners and Insterstitials in just few lines of code. It couldn’t be easier than that and I’ll show you.

Install the plugin

First of all, right click on your Xamarin solution and select “Manage Nuget packages for Solution”

manage nuget

Visual Studio will open a new screen where you can search and install one or more nuget packages. In this case we can search for the MTAdmob plugin. Searching for MarcTron will show you all my packages (I’m sure you can find other useful plugins that I’ve written), and we can select the MTAdmob plugin as showed in the next image.

It’s very important that you install the plugin in your PCL/.Net standard project and in your platform projects (Android, iOS, UWP).

After the Admob plugin is installed we can add banners and insterstitials to our projects.

Add Ads to our project

With version 1.0 the MTAdmob plugin supports banner and interstitials for Android and iOS. If you would like to see the plugin supporting also the UWP platform, let me now and I’ll add the support in a new version.

As I’ve said we can add Banners and Interstitials Admob ads to our project. Let’s start with the Banners

How to add an Admob Banner

An Admob banner is just a view inside our page. It means that we can add it using XAML or C#. First of all let’s see how to add an Admob banner using XAML.

Add an Admob Banner with XAML

In MTAdmob to use an Admob banner I’ve created a custom control called AdView, so to use it we can use this code:

<?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:controls="clr-namespace:MarcTron.Plugin.Controls;assembly=Plugin.MtAdmob"
             x:Class="Test.MTAdmob.MainPage">

<StackLayout>
    <Label Text="Let's test an Admob Banner!" 
           HorizontalOptions="Center"
           VerticalOptions="CenterAndExpand" />
    <!-- Place the Admob controls here -->
    <controls:AdView></controls:AdView>
</StackLayout>

In this example we have created a StackLayout with 2 controls: a label and an AdView (our Admob banner). Easy! Isn’t it???

The AdView control is basically a View so you can use all the properties you can think of like: HorizontalOptions, VerticalOptions, IsVisible…

In addition to these properties, I’ve added in AdView two other properties: AdsId and PersonalizedAds.

AdsId: Allows you to add the Banner Id (you can find it in your Admob account)

PersonalizedAds: This allow you to use non personalized ads. For example in case of GPDR. Of course it’s better to use personalized Ads.

To use these properties you can update the previous code to:

<controls:AdView PersonalizedAds="true" AdsId="xxxxxxxxxxxxxxxxxx"></controls:AdView>

Add an Admob Banner with C#

In case you don’t write your pages with XAML or you write your UI in C# or you want to add your view only in some cases, you can add your Admob Banner using this code:

using MarcTron.Plugin;
...
AdView ads = new AdView();

Of course you need to attach this View to your layout, but you know how to do it (If not, feel free to ask).

To use the custom properties you can change the previous code to:

...
AdView ads = new AdView();
ads.AdsId = "xxx";
ads.PersonalizedAds = true;

Also in this case, to add an Admob banner is INCREDIBILY EASY!!!

Global Custom Properties

As you have seen, the properties AdsId and PersonalizedAds belong to a single AdView. It means that you have to set them for every Admob Banner.

To make things even easier I’ve added the option to set these properties only once. To do so, you can use this C# code:

CrossMTAdmob.Current.UserPersonalizedAds = true;
CrossMTAdmob.Current.AdsId = "xxxxxxxxxxxxxxxx";

In this case all your Admob banner will show personalized ads and will have the same Id.

If you set local and global properties, the local ones will have higher priority.

Use of Banner Events

I’ve added 4 events to the Admob banner that you could find nice to have. These events are:

  • AdsClicked When a user clicks on the ads
  • AdsClosed When the user closes the ads
  • AdsImpression Called when an impression is recorded for an ad.
  • AdsOpened When the ads is opened

To use these events you can write this code:

AdView myAds = new AdView();
myAds.AdsClicked += MyAdsAdsClicked;
myAds.AdsClosed += MyAds_AdVClosed;
myAds.AdsImpression += MyAds_AdVImpression;
myAds.AdsOpened += MyAds_AdVOpened;

Of course you can use these events also if you have declared your AdView in your XAML code.

Admob Interstitials

Now that we know how to add Admob banners using my plugin MTAdmob, let’s see how we can add Admob Interstitials. If possible, to add an Admob interstitial is even easier. You just need a single line of code. Don’t you believe me? Look here how to show an Admob interstitial:

CrossMTAdmob.Current.ShowInterstitial("ca-app-pub-xxxxxxxxxxxxxxxx/xxxxxxxxxx");

I told you!!! That’s it!!! With that line of code you have just showed an Interstitial in you app. Of course you need to replace that string with the Insterstitial ID you can find in your Admob account.

Events for Interstitials

There 3 events that you can use with Interstitials:

OnInterstitialLoaded        When it's loaded
OnInterstitialOpened        When it's opened      
OnInterstitialClosed        When it's closed

Rewarded Video

From version 1.1 the plugin supports the amazing Rewarded Video too.

To show a rewarded video you just need a single line of code:

CrossMTAdmob.Current.ShowRewardedVideo("xx-xxx-xxx-xxxxxxxxxxxxxxxxx/xxxxxxxxxx");

Events for Rewarded videos

There are 7 events that you can use with the Rewarded video Ads:

OnRewarded                          When the user gets a reward
OnRewardedVideoAdClosed             When the ads is closed
OnRewardedVideoAdFailedToLoad       When the ads fails to load
OnRewardedVideoAdLeftApplication    When the users leaves the application
OnRewardedVideoAdLoaded             When the ads is loaded
OnRewardedVideoAdOpened             When the ads is opened
OnRewardedVideoStarted              When the ads starts

Initialization

Before you can use the Admob banners and Interstitials, you need to initialize it. You need to do it only once so it makes sense to initialize it onside the OnCreate method in Android and FinishedLaunching in iOS.

In your Android project add this line in your OnCreate method:

MobileAds.Initialize(ApplicationContext, "ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx");

In your iOS project add this line in your FinishedLaunching method:

MobileAds.Configure("ca-app-pub-xxxxxxxxxxxxxxxx~xxxxxxxxxx");

ANDROID PROJECT (IMPORTANT)

In your AndroidManifest you should add these lines:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application android:label="Test.MTAdmob.Android">
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>
    <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
</application>

Some useful links

Conclusion

This Admob MTAdmob plugin is incredibly easy to use but in case you need help, or you want to suggest a new feature or for any other reason, write me.

, , , , , , ,

About Author

23 Comments
  1. Eddy

    Hello,
    good jobs.
    How get event for interstitial and reward ads ?

    • Marco Troncone

      In this moment I’ve added only events for banners. I’ll try tomorrow to update the nuget package to add events also for interstitials.

      Are there any events/features you would like to see there?

      Marco

  2. Eddy Boughioul

    Hello,
    It can be interesting to have onRewardedVideoCompleted() and onAdClosed() for reward and interstitial
    TY

  3. Add Admob Rewarded video Ads to Android and iOS | Xamarin eXpert

    A detailed tutorial on how to use the plugin:
    https://www.xamarinexpert.it/blog/add-admob-rewarded-video-ads-to-android-and-ios-with-a-single-line-of-code/

  4. J0hs

    First of all thanks a lot for your plugins. This plugin and the SQL one has helped me a great deal.

    The interstitial works fine, but the banner ad gives me an error.

    System.TypeInitializationException: The type initializer for ‘MarcTron.Plugin.Controls.AdView’ threw an exception.

    • Marco Troncone

      Hi J0hs,
      Thanks for your comment.

      Can you give me more info about the error?
      What version of the plugin are you using? What version of Xamarin.Forms?
      On which platform do you get the error?

      The more information I get, the better I can help you.
      If you have also code that you thing makes sense to share,
      you can add an issue here:
      https://bitbucket.org/marcojak81/mtadmob/issues

      Thank you

      • J0hs

        I used my own implementation for the banner instead, and now it is working as intended. For the interstitial, I am still using the plugin.

        • Marco Troncone

          That’s good!

          But I’m sorry the banner didn’t work for you.
          What version of Xamarin.Forms are you using?

  5. Zoli

    REally nice PLugin, but unfortunately it’s not ok for Interstitials. As the load + show is in one function. The problem is, when you call it, the load takes 1-5 seconds (in the background), then show() is called. This makes it useless, as you cannot block your app for 5 seconds before displaying the Ad. Suggestion: in the constructor, already call load() for the app, and the current ShowInterstitial() should just call show(), which should be already loaded. Right after the .show(), you should re-load the next ad (still in the ShowInterstitial() ).
    Or, just make these functions public, and let the users call those.

    • Marco Troncone

      Hi Zoli,

      Thank you,
      This is a very good suggestion.
      I’ll try to change it during the weekend so that I can release soon a new version with the changes suggested.

    • Marco Troncone

      Hi Zoli,

      I’ve published the new version 1.2 of the MTAdmob plugin.

      Now there are 2 methods to Load and Show the plugin so you have total control over the interstitials and rewarded videos.
      For example to load an interstitial the method is “LoadInterstitial”. To show it is “ShowInterstitial”.
      There are also new methods to check if an interstitial or rewarded video are loaded.

  6. PILOT

    thank you so much marco. this is what I’m looking. ı trıed many times but ıt doesn’t work ın my project.

    I used that for Rewarded Videos but I got error lıke that {System.NotImplementedException: This functionality is not implemented in the portable version of this assembly.}

    • Marco Troncone

      You should install the library in every project, so your .NetStandard project AND your Android and iOS projects.
      If you install it only in your .NetStandard project, it will not work.

  7. ahmet

    hi mr. marco
    ı havent found out what ı am missıng but ı made all wrıttens step by step but when ı make archıve and transfer apk fıle to andorıd phone ı cant see my banner ads (google admob – Not testıng values)

    • Marco Troncone

      Hi Ahmet,

      Does it work in test mode?
      If it works in test mode, then it’s possible that Google still has to authenticate your account so you’ll need to wait few hours (I think up to 24 to receive actual ads).

      If it doesn’t work in test mode, have you tried to rotate the phone to see if you see the banner? sometimes you don’t have enough vertical space to show the ads. In that case you should set “HeightRequest” for the banner.

      Have you added your Ids for the Google Admob?

      Let me know if it solves your issue, otherwise we’ll continue to investigate.

  8. Douglas Dias Simao

    nOT SURE WHY FOR ME IT IS NOT WORKING, DO YOU HAVE A DEMO (GITHUB SOURCE) ?

    • Marco Troncone

      Yes, I’ll try to publish it this afternoon (I’ll write the link on the post and on a message).

      Meanwhile If you give me more information, I can try to help you. What problem do you have with the plugin?

    • Marco Troncone

      Hi Douglas,

      I’ve added the demo project on Github. You can download it here: https://github.com/marcojak/TestMTAdmob
      If you have any issue with it let me know, and I’ll try to help you

  9. Mitch H.

    Is there the ability to add test device ID’s so the ads will display when testing on physical devices vs. the emulator? I’ve tried adding a test Device in the MainActivity.cs after the MobileAds.Initialize but I still receive the error in the App output that the ads fail to load and to add the test device.

    • Mitch H.

      Figured it out – sorry I didn’t realize the Test devices were part of CrossMTAAdMob.Current. Great plugin. Many thanks.

Leave a Reply

%d bloggers like this: