locked
AdMob and Xamarin.forms RRS feed

  • Question

  • User12885 posted

    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?

    Tuesday, September 1, 2020 4:24 PM

All replies

  • User365353 posted

    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/

    Tuesday, September 1, 2020 5:09 PM
  • User12885 posted

    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.

    Tuesday, September 1, 2020 5:19 PM
  • User365353 posted

    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.

    Tuesday, September 1, 2020 5:38 PM
  • User12885 posted

    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

    Tuesday, September 1, 2020 6:19 PM
  • User12885 posted

    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.

    Friday, September 4, 2020 5:17 PM
  • User12885 posted

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

    Saturday, September 5, 2020 6:17 PM
  • User365353 posted

    How is your progress?

    Sunday, September 6, 2020 5:38 PM
  • User12885 posted

    No change.

    Sunday, September 6, 2020 5:42 PM
  • User12885 posted

    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.

    Sunday, September 6, 2020 9:30 PM
  • User12885 posted

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

    Sunday, September 6, 2020 9:49 PM
  • User365353 posted

    Does the code from this post work?

    Monday, September 7, 2020 7:03 PM
  • User12885 posted

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

    I am just about done writing up what worked.

    Monday, September 7, 2020 7:30 PM
  • User12885 posted

    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:

    ```csharp 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 <?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:

    ```csharp 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:

    ```csharp 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 { 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 <?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

    Monday, September 7, 2020 7:41 PM
  • User300148 posted

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

    Thursday, September 24, 2020 1:36 AM
  • User199608 posted

    @Corwyn Nice work. Did you get this to work in ios as at all. ? Isnt there a forms solutions for this at all? Seems elementary for cross platform

    Saturday, November 7, 2020 7:02 PM
  • User12885 posted

    @"RobertDunn.2723" I don't do iOS

    Saturday, November 7, 2020 9:54 PM
  • User300148 posted

    Hey, I ended up with a functional Rwarded Ad setup that you can look at here - https://github.com/aormsby/Xamarin-AdMob

    I apologize for the messy repo and code, and I'm actually thinking it's not even the most up-to-date version of what I wrote. However, it may give you something to help guide you to what you need. If you have any trouble following it, just ping me for help. I'm happy to point things out. I'll try and remember to add any outstanding updates in the next few days. Cheers.

    Sunday, November 8, 2020 1:36 AM
  • User381617 posted

    Corwyn - I've been having these issues as well. I got ads working on iOS but I still get: using Android.Gms.Ads; as not existing which is what you wrote here on September 9. Xamarin.GooglePlayServices.Ads.Lite v119.1.0 is installed. Can you tell me explicitly what you did to locate it? Do I just need an earlier version of the NuGet package?

    Tuesday, November 10, 2020 6:00 AM
  • User245203 posted

    Personally I would use this.

    https://github.com/marcojak/MTAdmob I got it working on iOS and Android super easy.

    Tuesday, November 10, 2020 11:59 AM
  • User12885 posted

    @Grime said: Corwyn - I've been having these issues as well. I got ads working on iOS but I still get: using Android.Gms.Ads; as not existing which is what you wrote here on September 9. Xamarin.GooglePlayServices.Ads.Lite v119.1.0 is installed. Can you tell me explicitly what you did to locate it? Do I just need an earlier version of the NuGet package?

    My issue was that it was installed to the shared project. That was causing the not found. It should only be installed to the Android (and presumably) iOS projects.

    Tuesday, November 10, 2020 2:30 PM
  • User381617 posted

    @Corwyn said:

    @Grime said: Corwyn - I've been having these issues as well. I got ads working on iOS but I still get: using Android.Gms.Ads; as not existing which is what you wrote here on September 9. Xamarin.GooglePlayServices.Ads.Lite v119.1.0 is installed. Can you tell me explicitly what you did to locate it? Do I just need an earlier version of the NuGet package?

    My issue was that it was installed to the shared project. That was causing the not found. It should only be installed to the Android (and presumably) iOS projects.

    Thanks. I ended up going over notes I had from 6 months ago and I saw I had a similar problem (couldn't find Android.Gms.Ads) and back then I just saved and rebooted and then it was magically "found". Did the same yesterday.

    Tuesday, November 10, 2020 10:30 PM
  • User393049 posted

    @Corwyn I did all step of yours but I don't see ads in my project and I didn't get any error. Please help me, How can I do it?

    Friday, November 13, 2020 11:24 AM
  • User12885 posted

    @ZeyarWinThu said: @Corwyn I did all step of yours but I don't see ads in my project and I didn't get any error. Please help me, How can I do it?

    @ZeyarWinThu Were you able to get my sample project to work?

    Friday, November 13, 2020 3:43 PM
  • User393049 posted

    @Corwyn I downloaded your project and I can run it. When I use your ad unit and app id I see 'test ad nice job'. But when I use my own ad unit and app id, I didn't see any ads.

    Friday, November 13, 2020 4:15 PM
  • User12885 posted

    @ZeyarWinThu And you updated the approriate lines with your application ID?

    Friday, November 13, 2020 4:32 PM
  • User393049 posted

    @Corwyn I updated AndroidManifest.xml and MainActivity.cs with my app ID.

    Saturday, November 14, 2020 5:05 AM
  • User393049 posted

    @Corwyn My app id and your ad unit id is show "test ad nice job" But My app id and my ad unit id is not work.

    Saturday, November 14, 2020 1:47 PM
  • User12885 posted

    How long ago did you sign up with ad mob to get the ad unit id? It took a while before mine was active. And when you say it works with my app unit id as opposed to yours what id is that?

    Saturday, November 14, 2020 6:21 PM
  • User393049 posted

    @Corwyn I sign up ad mob one week ago. I use my app id and test unit id 'ca-app-pub-3940256099942544/6300978111' It is work.

    Thursday, November 19, 2020 4:01 AM
  • User393049 posted

    @Corwyn I found request in my app(google admob) but I never see ad in my app.

    Saturday, November 21, 2020 5:52 PM
  • User12885 posted

    @ZeyarWinThu it is difficult to know what the issue might be. Have you clicked the help on that page and reviewed the "Common reasons for ads not showing"

    Saturday, November 21, 2020 6:01 PM
  • User12885 posted

    Also, check out the AdMobs community, this appears to be a common issue: https://support.google.com/admob/community?hl=en

    Saturday, November 21, 2020 6:06 PM
  • User393049 posted

    @Corwyn thanks for your support.

    Saturday, November 21, 2020 6:11 PM
  • User398747 posted

    I used this guide, it was straight forward

    AdMob In Xamarin.Forms – Display Google Ads In Your Mobile App Posted: February 17, 2018 / By: Adam Pedley/ In: Advertising *Cant post links yet.

    The initializers have been deprecated and are now a little different.

    The guide is also missing the iOS info.plist requirement that was introduced since the guide was written.

    <key>GADApplicationIdentifier</key> <string>ca-app-pub-3940256099942544~1458002511</string> <key>SKAdNetworkItems</key> <array> <dict> <key>SKAdNetworkIdentifier</key> <string>cstr6suwn9.skadnetwork</string> </dict> </array>

    Thursday, December 31, 2020 3:44 PM
  • User399016 posted

    @Corwyn Thank you Sir! You are a lifesaver. This is the only post which shows a pure implementation of Admob in Xamarin forms without any third party Admob Nuget dependencies.

    The only quirk I noticed was shows a deprecated warning, although the app worked with the warning (running on the emulator)

    I replaced it with

    MobileAds.Initialize(Android.App.Application.Context);

    which I got from an Android Admob post, please let me know if that makes sense.

    (Also FYI I have replaced your Admob ID, but using yours only for this post :) )

    And Incase anybody was wondering the versions I've used are as follows

    <ItemGroup> <PackageReference Include="Xamarin.Forms" Version="5.0.0.1874" /> <PackageReference Include="Xamarin.Essentials" Version="1.6.0" /> <PackageReference Include="Plugin.CurrentActivity"> <Version>2.1.0.4</Version> </PackageReference> <PackageReference Include="Xamarin.GooglePlayServices.Ads"> <Version>71.1720.4</Version> </PackageReference> </ItemGroup>

    Sunday, January 17, 2021 10:59 PM
  • User284313 posted

    About filling the forms relating data collection over SKAdNetwork, at app store publishing phase, below is a helpful article:

    Filling out the App Privacy Section in App Store Connect for AdMob Users

    Wednesday, March 3, 2021 6:30 AM
  • User292187 posted

    I am getting this kind of error when trying to build the android app. I am usingXamarin.Firebase.Ads.Lite and Xamarin.GooglePlayServices.Ads.Lite nuget packages. Rest of the code is same. Custom view,Custom renderer for android etc. How can I get rid of these errors ?

    Friday, March 12, 2021 7:59 AM
  • User12885 posted

    @gayugokhale said:

    I am getting this kind of error when trying to build the android app. I am usingXamarin.Firebase.Ads.Lite and Xamarin.GooglePlayServices.Ads.Lite nuget packages. Rest of the code is same. Custom view,Custom renderer for android etc. How can I get rid of these errors ?

    Definitely non specific errors there. Is it possibly an upgrade issue? You might see if this will help: https://github.com/xamarin/AndroidX/issues/72

    Friday, March 12, 2021 3:04 PM