Forum Xamarin Xamarin.Forms

AdMob and Xamarin.forms

CorwynCorwyn USMember ✭✭✭

I have been through the forums and searches online and I have yet to find any samples or tutorials that work to get AdMob working with Xamarin Forms.

Does anyone know of a current admob tutorial, within the last... say 9 months... tutorial or sample that works with xamarin forms?

Tagged:

Posts

  • igorkr_10igorkr_10 Member ✭✭✭✭

    The solution is standard:
    1. Create a custom view in shared project.
    2. Initialize Admob in platform.
    3. Create renderer in platform project to transfer platform view to your shared project.
    4. Use custom view.

    https://www.codeproject.com/Tips/1275283/Xamarin-Forms-Integration-with-Google-Admob
    https://montemagno.com/xamarinforms-google-admob-ads-in-android/
    https://www.xamarinhelp.com/admob-xamarin-forms-display-google-ads-mobile-app/

  • CorwynCorwyn USMember ✭✭✭

    Thanks for the response.
    Thirst first one looks promising but has a basic issue that they all have:
    Where do you get Android.Gms.Ads;?

    For the other two Jame's post is 4 years out of date and does not work.
    I followed the last one and found I could not get it to work either.

  • igorkr_10igorkr_10 Member ✭✭✭✭

    Where do you get Android.Gms.Ads;?

    Try to install in NuGet Xamarin.GooglePlayServices.Ads.Lite or Xamarin.GooglePlayServices.Ads
    I have found those libraries in Android sample.

  • CorwynCorwyn USMember ✭✭✭

    Whenever I tried and install either of those two into a xamarin forms project I get the following error.

    Severity Code Description Project File Line Suppression State
    Error NU1202 Package Xamarin.GooglePlayServices.Ads 71.1720.4 is not compatible with netstandard2.0 (.NETStandard,Version=v2.0). Package Xamarin.GooglePlayServices.Ads 71.1720.4 supports: monoandroid90 (MonoAndroid,Version=v9.0) App4 C:\Users\corwyn\source\repos\App4\App4\App4\App4.csproj 1

  • CorwynCorwyn USMember ✭✭✭

    Ok, I have figured out the install issue. The plugin must not be installed to the shared project, just the specific mobile project. Android in my case.

    Still unable to get test ads to render though.

  • CorwynCorwyn USMember ✭✭✭

    I am still battling with trying to get ads to show. Is there anything below that stands out as being wrong?
    https://github.com/DonGlover/AdMobTest

    In my MainActivity.cs I have (wiht an appropriate app ID):

                Xamarin.Essentials.Platform.Init(this, savedInstanceState);
                MobileAds.Initialize(ApplicationContext, "ca-app-pub-xxxxxxxxx");
                global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
                LoadApplication(new App());
    

    I have a AdMobViewRenderer.cs:

    [assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
    namespace AdMobTest.Droid
    {
        public class AdMobViewRenderer : ViewRenderer<AdMobView, AdView>
        {
            public AdMobViewRenderer(Context context) : base(context) { }
    
            protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
            {
                base.OnElementChanged(e);
    
                if (e.NewElement != null && Control == null)
                {
                    SetNativeControl(CreateAdView());
                }
            }
    
            protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
            {
                base.OnElementPropertyChanged(sender, e);
    
                if (e.PropertyName == nameof(AdView.AdUnitId))
                    Control.AdUnitId = Element.AdUnitId;
            }
    
            private AdView CreateAdView()
            {
                var adView = new AdView(Context)
                {
                    AdSize = AdSize.SmartBanner,
                    AdUnitId = Element.AdUnitId
                };
    
                adView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
    
                adView.LoadAd(new AdRequest
                                .Builder()
                                .Build());
    
                return adView;
            }
    
        }
    }
    

    In my AndroidManifest.xml:

        <application android:label="AdMobTest.Android" android:theme="@style/MainTheme">
          <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
          <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-3940256099942544~1458002511"/>
          <meta-data android:name="com.google.android.gms.ads.AD_MANAGER_APP" android:value="true"/>
        </application>
    

    An AdMobView.cs with:

    namespace AdMobTest.controls
    {
        public class AdMobView : View
        {
            public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(
                       nameof(AdUnitId),
                       typeof(string),
                       typeof(AdMobView),
                       string.Empty);
    
            public string AdUnitId
            {
                get => (string)GetValue(AdUnitIdProperty);
                set => SetValue(AdUnitIdProperty, value);
            }
        }
    }
    

    Everything is in:

    https://github.com/DonGlover/AdMobTest

  • igorkr_10igorkr_10 Member ✭✭✭✭

    How is your progress?

  • CorwynCorwyn USMember ✭✭✭

    No change.

  • CorwynCorwyn USMember ✭✭✭

    Update...

    On the Plus side:
    I finally got ad serving working in my test app.
    On the Minus side:
    I am not sure what I did that got it to start working.

  • CorwynCorwyn USMember ✭✭✭

    Replicated the code into my actual app and it works there.

  • igorkr_10igorkr_10 Member ✭✭✭✭

    Does the code from this post work?

  • CorwynCorwyn USMember ✭✭✭

    No, there was at least one error in it that I had copied from elsewhere.

    I am just about done writing up what worked.

  • CorwynCorwyn USMember ✭✭✭
    edited September 7

    Recently, I spent some time banging my head against the wall attempting to figure out how to add AdMob ads to my app. I read through all of the existing recommended blog posts and articles on the subject. I delved into stackoverflow. I even perused the official documentation.

    I decided that I needed to simplify and see if I could get it working in a sample app; then move it to my full app. (Spoiler alert I succeeded.)

    I am sharing what worked for me.

    I created an AdMob account at https://admob.google.com/home/

    I created a Blank Android Mobile App called AdMobSample.

    Create Mobile app in Visual Studio

    I selected the "Blank" template to create what Microsoft calls an "empty app". In reality, it creates a simple single-page app the is useful when you are trying out new techniques. At this time, I am only interested in Android apps so I made sure to uncheck iOS which is typically checked by default.

    Create an empty app

    I added the Xamarin.GooglePlayServices.Ads plug-in to the app. Note: I initially made the mistake of installing it for all the projects in the app. This caused the plug-in to fail to install with an error message that the plug-in is not compatible with .NET 2.0.

    In the MainActivity.cs file of the Android Project, I added a using statement to reference Ads namespace:

    using Android.Gms.Ads;

    In the OnCreate method, I initialized the ads by calling MobileAds.Initialize:

    base.OnCreate(savedInstanceState);
    
    // Replace the app id with your app ID from Google AdMob
    MobileAds.Initialize(ApplicationContext, "ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy");
    Xamarin.Essentials.Platform.Init(this, savedInstanceState);
    global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
    LoadApplication(new App());
    

    I modified the AndroidManifest.xml file located in the Properties folder of the Android project as follows:

    <?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.admobsample">
        <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
        <application android:label="AdMobSample.Android" android:theme="@style/MainTheme">
          <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
          <meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy" />
          <meta-data android:name="com.google.android.gms.ads.AD_MANAGER_APP" android:value="true" />
        </application>
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    </manifest>
    

    To display the ad I had to add a view in the shared project. For more information on implementing a view, see Implementing a View.

    In the shared project I added AdMobView.cs:

    using Xamarin.Forms;
    
    namespace AdMobSample.controls
    {
        public class AdMobView : View
        {
            public static readonly BindableProperty AdUnitIdProperty = BindableProperty.Create(
                       nameof(AdUnitId),
                       typeof(string),
                       typeof(AdMobView),
                       string.Empty);
    
            public string AdUnitId
            {
                get => (string)GetValue(AdUnitIdProperty);
                set => SetValue(AdUnitIdProperty, value);
            }
        }
    }
    

    To create the view for Android I had to a custom view renderer. After the view is created you call SetNativeControl() to display it. For more information on view renderers, see .

    In Android project I added AdMobViewRenderer.cs:

    using System.ComponentModel;
    using AdMobSample.controls;
    using AdMobSample.Droid;
    using Android.Content;
    using Android.Gms.Ads;
    using Android.Widget;
    using Xamarin.Forms;
    using Xamarin.Forms.Platform.Android;
    
    [assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobViewRenderer))]
    namespace AdMobSample.Droid
    {
        public class AdMobViewRenderer : ViewRenderer<AdMobView, AdView>
        {
            public AdMobViewRenderer(Context context) : base(context) { }
    
            protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e)
            {
                base.OnElementChanged(e);
    
                if (e.NewElement != null && Control == null)
                {
                    SetNativeControl(CreateAdView());
                }
            }
    
            protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
            {
                base.OnElementPropertyChanged(sender, e);
    
                if (e.PropertyName == nameof(AdView.AdUnitId))
                    Control.AdUnitId = Element.AdUnitId;
            }
    
    
            private AdView CreateAdView()
            {
                var adView = new AdView(Context)
                {
                    AdSize = AdSize.SmartBanner,
                    AdUnitId = Element.AdUnitId
                };
    
                adView.LayoutParameters = new LinearLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
    
                adView.LoadAd(new AdRequest
                                .Builder()
                                .Build());
    
                return adView;
            }
        }
    }
    

    Finally, I modified the MainPage.xaml by adding a reference to the view xmlns:local="clr-namespace:AdMobSample.controls" and I added the control in a stacklayout as follows <local:AdMobView AdUnitId="ca-app-pub-3940256099942544/6300978111" WidthRequest="320" HeightRequest="50"/>:

    <?xml version="1.0" encoding="utf-8" ?>
    <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:local="clr-namespace:AdMobSample.controls"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 x:Class="AdMobSample.MainPage">
        <StackLayout>
            <Label Text="Display an Admob Banner!" 
               HorizontalOptions="Center"
               VerticalOptions="CenterAndExpand" />
            <!-- Place the Admob controls here -->
            <local:AdMobView AdUnitId="ca-app-pub-3940256099942544/6300978111" WidthRequest="320" HeightRequest="50"/>
        </StackLayout>
    </ContentPage>
    

    Note: If you do not specify a width and Height request the ad does not display.

    I have created a GitHub repo with my working sample:
    https://github.com/DonGlover/DonGlover-AdMobSample

  • aormsbyaormsby USMember ✭✭

    Recently, I spent some time banging my head against the wall attempting to figure out how to add AdMob ads to my app.

    Yes, this is what I am doing right now, and I feel your pain deeply. Except I'm trying to implement rewarded ads, which it seems even fewer people have tried. :D I got Android so far, but not iOS.

    Nice work on the banners, basically what I did. Now if I could just figure out rewarded ads for iOS.......

Sign In or Register to comment.