NuGetXamarinXamarin.Forms

Xamarin.Forms AdMob Interstitial Banner Awarded Ads

Contents

It is possible to earn money by adding AdMob ads to your Xamarin.Forms applications. However, to do this, you must first create Dependecy classes for each ad unit on native platforms and then call these classes in Xamarin.Forms. This brings many workloads.

However, there is no need to try that much. Using the MTAdmob plugin, you can show AdMob ads in your Xamarin.Forms applications with a few lines of code. So you don’t waste time creating individual Dependency classes.

MTAdmob plugin is a NuGet package developed by Marco Troncone. This plugin allows you to show AdMob ads to your Xamarin projects with just a few lines of code. You can examine plugin here.

In this article, I will explain how to place AdMob ads in your Xamarin.Forms applications using the MTAdmob plugin.

1) Install the MTAdmob plugin in your project

First, install the MarcTron.Admob NuGet package in your Xamarin.Forms project.

Type the following code in the Package Manager Console and run it. (Install and Manage NuGet Packages)

Install-Package MarcTron.Admob -Version 1.6.1

Alternatively, you can install this plugin from NuGet Package Manager. (Install and Manage NuGet Packages)

Xamarin.Forms MarcTron AdMob NuGet Package
Install the MarcTron.AdMob plugin to your project

After the plugin is installed, a readme.txt file will open, which includes warnings about this plugin and how to use the plugin. In this file, you can review the notes and instructions on the versions of the plugin.

Xamarin.Forms MarcTron AdMob NuGet Package ReadMe
You can view warnings and instructions in the readme.txt file.

2) Add the AdMob application ID to your project

In order to show AdMob ads in your application, you must add the application ID you get from your AdMob account to your project. However, if the application is not completed yet, it is useful to use test ads instead of your own ads.

Because you can check whether the ads are working properly by clicking the test ads while the application is in the development phase. If you click your own ads too many times without being in test mode, your AdMob account may be restricted due to invalid clicks.

After the implementation is complete, replace the test ads with the ad units you create from your AdMob account.

Use test ad units and IDs provided by Google to enable test ads. Since these ad units are not associated with your AdMob account, there is no risk of your account generating invalid traffic when using these ad units.

  • App ID for Android ca-app-pub-3940256099942544 ~ 3347511713
  • App ID for iOS ca-app-pub-3940256099942544 ~ 1458002511
  • Banner ca-app-pub-3940256099942544/6300978111
  • Interstitial ca-app-pub-3940256099942544/1033173712
  • Rewarded ca-app-pub-3940256099942544/5224354917

Android

Open the Android/Properties/AndroidManifest.xml file in your project. Then add your application ID between <application> tags.

To display test ads here, first add the app ID provided by Google instead of your own app ID. After testing the application, replace the application ID you create from your AdMob account with the test ID.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.weather">
	<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="29" />
	<application android:label="Weather.Android">
		<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID"
           android:value="ca-app-pub-3940256099942544~3347511713"/>
	</application>
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

iOS

Right-click on the Info.plist file in your app’s iOS folder and select Open With. Then choose XML (Text) Editor in the window that opens.

Xamarin.iOS info plist Open With XML Text Editor
Open the Info.plist file with the XML Text Editor

Then add your app ID between the <dict> tags in the Info.plist file.

<key>GADApplicationIdentifier</key>
<string>ca-app-pub-3940256099942544~1458002511</string>
<key>GADIsAdManagerApp</key>
<true/>
Xamarin.iOS info plist add AdMob application id
Add your application ID to the info.plist file

3) Initialize the MTAdmob plugin

To use the MTAdmob plugin in your Xamarin.Forms project, you must initialize this plugin on each platform.

Android

Call the Initialize() method of the MTAdmob plugin inside the onCreate() method of the MainActivity.cs class.

protected override void OnCreate(Bundle savedInstanceState)
{
    // Your other codes
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    //Call the initialize method of MTAdmob plugin
    MobileAds.Initialize(ApplicationContext);
    LoadApplication(new App());
}

iOS

Go to AppDelegate.cs class to launch MTAdmob plugin on iOS platform. Then call the initiator method inside the FinishedLaunching() method. So every time the AppDelegate class runs, the MTAdmob plugin will start.

public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
    global::Xamarin.Forms.Forms.Init();
    
    MobileAds.Configure("ca-app-pub-3940256099942544~1458002511");
    LoadApplication(new App());
    return base.FinishedLaunching(app, options);
}

4) Add banner ad to your app

After initialize the plugin, you can now add ads to your app.

I will first add the banner ad and then the interstitial and rewarded ad units to this sample project.

1 Now add a new ContentPage to your project named AdMobPage.xaml.

2 Then add the required namespace to the ContentPage definition in order to use the MTAdmob plugin in XAML.

xmlns:controls="clr-namespace:MarcTron.Plugin.Controls;assembly=Plugin.MtAdmob"
Xamarin.Forms Content Page MTAdmob Namespace
Add XAML namespace

3 Then add the AdMob banner ad in ContentPage as follows.

Note that I have included a test ad ID for Android and iOS platforms separately here. Because an ad unit has different ad IDs for Android and iOS platforms.

If your ads are not visible, set the HeightRequest value.

<?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="Weather.View.AdMobPage">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />

            <controls:MTAdView x:Name="myAds" 
                               AdsId="{OnPlatform Android='ca-app-pub-3940256099942544/6300978111', 
                                                  iOS='ca-app-pub-3940256099942544/2934735716'}"
                               HeightRequest="50"/>
            
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

Run the application and check if the test ad appears.

Xamarin.Forms AdMob Banner Ad
Xamarin.Forms AdMob Banner Ad

5) Add interstitial and rewarded ad to your app

1 Now add two buttons named Interstitial and Rewarded into AdMobPage.xaml and define the Clicked events of these buttons.

<?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="Weather.View.AdMobPage">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Welcome to Xamarin.Forms!"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
            
            <Button Text="Interstitial" Clicked="Interstitial_Clicked"/>
            <Button Text="Rewarded" Clicked="Rewarded_Clicked"/>
            
            <controls:MTAdView x:Name="myAds" 
                               AdsId="{OnPlatform Android='ca-app-pub-3940256099942544/6300978111', 
                                                  iOS='ca-app-pub-3940256099942544/2934735716'}"
                               HeightRequest="50"/>
            
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

2 Then go to AdMobPage.xaml.cs class and fill in Clicked methods and constructor method as below. Include the test ad ID separately for interstitial and rewarded ad.

public partial class AdMobPage : ContentPage
{
    public AdMobPage()
    {
        InitializeComponent();
        CrossMTAdmob.Current.OnInterstitialLoaded += (s, args) => {
            CrossMTAdmob.Current.ShowInterstitial();
        };
        CrossMTAdmob.Current.OnRewardedVideoAdLoaded += (s, args) => {
            CrossMTAdmob.Current.ShowRewardedVideo();
        };
    }
    private void Interstitial_Clicked(object sender, EventArgs e)
    {
        CrossMTAdmob.Current.LoadInterstitial("ca-app-pub-3940256099942544/1033173712");
    }
    private void Rewarded_Clicked(object sender, EventArgs e)
    {
        CrossMTAdmob.Current.LoadRewardedVideo("ca-app-pub-3940256099942544/5224354917");
    }
}

When you click the Interstitial button here, the interstitial ad is loaded. Then the advertisement is displayed when the OnInterstitialLoaded event handler in the constructor method is triggered. So, first, by clicking the button, you upload the ad. Then the event handler is triggered as soon as the ad is loaded and the ad starts to appear. The rewarded button works in the same way.

Xamarin.Forms AdMob interstitial ad
Xamarin.Forms AdMob interstitial ad

6) Replace test ads with your own

After you’ve tested the ads in your app, replace the test ads IDs with your own.

Conclusion

In this article, I explained how to place AdMob ads in your Xamarin.Forms applications using the MTAdmob plugin. I hope it was useful.

If you’re still not sure what to do, or if you got any errors, then I suggest you use the comment section below and let me know! I am here to help!

Also, share this blog post on social media and help more people learn.

Serkan

Software Engineer. Problem solver. Music practitioner. Thinker. Industrious.

Related Articles

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button