Click here to Skip to main content
15,867,308 members
Articles / Mobile Apps / Xamarin
Tip/Trick

Xamarin Forms Integration with Google Admob

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
24 Jan 2019CPOL2 min read 15.9K   699   3   3
This article with help monetize your Xamarin Forms app using Google Admob. This article shares different implementations for Xamarin.iOS and Xamarin.Android.

Introduction

This project showcases how to use Google's Admob for monetizing your Xamarin Forms mobile app for Android and iOS platforms. You can also check out the video tutorial. I'm sure there are plenty of ways of implementing Admob and many of the ways will be better than mine. If you know any better way or have any suggestions for me, please share with me. I'd love to hear it.

Background

Before you begin, you need to have an account on Admob. If you don't have an account, please create an account and then proceed with this article. Also, you need to know some of the basic concepts of Xamarin forms like implementing a view.

Using the Code

Portable Library

We start by creating our custom control AdmobControl which extends View class.

C#
public class AdmobControl : View
   {
       public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(
                      nameof(AdUnitId),
                      typeof(string),
                      typeof(AdmobControl),
                      string.Empty);

       public string AdUnitId
       {
           get => (string)GetValue(AdUnitIdProperty);
           set => SetValue(AdUnitIdProperty, value);
       }
   }

Then we use the AdmobControl in our view. Here's a simple example from this project.

C#
public MainPage()
        {
            InitializeComponent();
            AdmobControl admobControl = new AdmobControl()
            {
                AdUnitId = AppConstants.BannerId
            };
            Label adLabel = new Label() { Text = "Ads will be displayed here!"};

            Content = new StackLayout()
            {
                Children = { adLabel, admobControl }
            };

            this.Title = "Admob Page";
        }

Android Implementation

The first step is to configure our application with Admob App Id. This needs to be done in MainActivity.cs.

C#
using Android.Gms.Ads;

MobileAds.Initialize(ApplicationContext, '{Your App ID}');

The next step is to allow permissions for the app in AndroidManifest.xml:

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

We also need to define the AdActivity in the manifest:

XML
  <activity android:name="com.google.android.gms.ads.AdActivity" 
   android:configChanges="keyboard|keyboardHidden|orientation|
                          screenLayout|uiMode|screenSize|smallestScreenSize"
   android:theme="@android:style/Theme.Translucent" />

Now, we need to create the platform specific renderer for AdmobControl. This will be different for all platforms.

C#
[assembly: ExportRenderer(typeof(AdmobControl), typeof(AdMobRenderer))]
namespace Xamarin.AdmobExample.Droid.Implementations
{
    public class AdMobRenderer : ViewRenderer<AdmobControl, AdView>
    {
        public AdMobRenderer(Context context) : base(context)
        {
        }

        private int GetSmartBannerDpHeight()
        {
            var dpHeight = Resources.DisplayMetrics.HeightPixels / Resources.DisplayMetrics.Density;

            if (dpHeight <= 400)
            {
                return 40;
            }
            if (dpHeight <= 720)
            {
                return 62;
            }
            return 102;
        }

        protected override void OnElementChanged(ElementChangedEventArgs<AdmobControl> e)
        {
            base.OnElementChanged(e);

            if (Control == null)
            {
                var adView = new AdView(Context)
                {
                    AdSize = AdSize.SmartBanner,
                    AdUnitId = Element.AdUnitId
                };

                var requestbuilder = new AdRequest.Builder();

                adView.LoadAd(requestbuilder.Build());
                e.NewElement.HeightRequest = GetSmartBannerDpHeight();

                SetNativeControl(adView);
            }
        }
    }
}

We're all set with Android Implementation. We can now start testing.

iOS Implementation

Similar to Android, we need to configure our App Id in the app. In iOS, we configure it in AppDelegate.cs:

C#
Google.MobileAds.MobileAds.Configure('{Your App Id}');

Now, we'll write the iOS renderer for AdmobControl:

C#
[assembly: ExportRenderer(typeof(AdmobControl), typeof(AdMobViewRenderer))]
namespace Xamarin.AdmobExample.iOS.Implementations
{
    [Protocol]
    public class AdMobViewRenderer : ViewRenderer<AdmobControl, BannerView>
    {

        protected override void OnElementChanged(ElementChangedEventArgs<AdmobControl> e)
        {
            base.OnElementChanged(e);
            if (Control == null)
            {
                SetNativeControl(CreateBannerView());
            }
        }

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            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;
        }
    }
}

We're now ready to run the application and start earning.

Points of Interest

I was surprised to know how these nuget packages and libraries are so developed by now that they give the feel of natively built apps in terms of performance and user experience.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
I'm an aspiring Developer recently started more and more interested towards ASP.NET and related technologies. I tend to love playing around with different technologies and get more hands on experience by working on different projects. My prime interest lies in Mobile Development(both native and hybrid) and have developed few basic application during my course of studies and work. Always up for a challenge and plan on to finish it through best possible approach.

Comments and Discussions

 
QuestionDont Work with my own adds Pin
Member 1174426121-Jan-20 10:23
Member 1174426121-Jan-20 10:23 
QuestionNative Ads Pin
MAH Clark23-Sep-19 10:19
MAH Clark23-Sep-19 10:19 
GeneralMy vote of 5 Pin
MR-dds7-Apr-19 9:51
MR-dds7-Apr-19 9:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.