Click here to Skip to main content
13,898,359 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

2K views
37 downloads
2 bookmarked
Posted 24 Jan 2019
Licenced CPOL

Xamarin Forms Integration with Google Admob

, 24 Jan 2019
Rate this:
Please Sign up or sign in to vote.
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.

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.

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.

using Android.Gms.Ads;

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

The next step is to allow permissions for the app in AndroidManifest.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:

  <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.

[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:

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

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

[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)

Share

About the Author

Harshit Gindra
Web 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.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190306.1 | Last Updated 24 Jan 2019
Article Copyright 2019 by Harshit Gindra
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid