crop faceless person demonstrating sign sale
Photo by Sora Shimazaki on Pexels.com

It took me ages to figure out how to get Googles AdMob adverts into our little Android monogame game Jumpy Kitty, looking over the internet there’s loads of bits of how you can/could do it – but none worked for me. Most examples had lots of errors which seemed like some of the dependent nuget packages were either broken or had changed since the examples had been written. Also, none seemed to work with the latest version of monogame (3.8.1 at the time of writing) and .NET 6/7/8 that we’re using for our game.

In short, it was something I first thought would dead simple before I started looking into it, but turned out to be a real pain in the a** to figure out. Also, most of the examples for AdMob are geared towards Java, not C# and monogame…

person holding brown and white paper
Photo by Poppy Thomas Hill on Pexels.com

All I wanted was a little banner advert section at the bottom of the screen on my game, how hard should that be I thought? I also tried numerous nuget packages that people had built which purported to do this for you, but those either targeted XAML or MAUI, or didn’t have any simple example of the code needed to implement them, or they didn’t work with the latest version of monogame and .NET 6 or .NET 8.

Most of this is based off various parts of code from this thread (scroll down and around a bit) in the monogame community posts pages, so I’ve got to give some credit for this to the authors there. After looking through this and several other sites and blogs though, in the end it actually did boil down to being reasonably simple (at least for my banner ad).

FYI – I only wanted a banner ad for our game, but if you read the thread listed above there are various other types of ad’s listed in the code. However, for me not all the code seemed necessary for my purposes and there were lots of classes showing errors like they now didn’t exist. In short, I removed all the code I didn’t need. I think someone mentions on the thread somewhere that Google had refactored their API which has broken some stuff in the Xamarin nuget packages, I’m guessing that’s why some of the code now doesn’t work.

man crying on field
Photo by Jim De Ramos on Pexels.com

I’ll leave the pain of setting up an actual AdMob account to someone else to explain, that’s a whole other story, as it you’ll probably find that harder and have it take longer than modifying your code! Assuming you can actually get an account without being rejected for no apparent reason or having your app disabled for invalid activity or something else.

Be prepared for a hard time, with poor support from Google and no human to talk to… Well, apart from sending you to a forum for community members to try and help. To be honest, I’ve begun looking to see if there’s a ad provider with better support and less aggressive rejection and disabling tendencies. There is of course no perfect provider, but the pain of trying to get AdMob setup really is a put off, it should be much easier and clearer with far better support. I’ll do a follow up post if I ever get anywhere and migrate away from AdMob…

strong sportsmen ready for running on stadium
Photo by Andrea Piacquadio on Pexels.com

So, I’m making an assumption here that you’ve already managed to successfully setup an AdMob account, created an ‘app’ in there for your game and also created an ‘ad unit’ for a banner. Note that I’m just creating a banner ad for this example, although it should be fairly easy to modify to display other ad types. Also note that at the time of writing I’m using monogame version 3.8.1 (latest version as of May 2024), plus I’ve updated my *.csproj files to target .NET 8 (although this should work the same for .NET 6). So, you’ll need to do (at minimum) the following 3 steps:-

  • Modify your ‘AndroidManifest.xml’ file in your monogame Android project to put in your AdMob app details and some other requirements
  • Add the ‘Xamarin.GooglePlayServices.Ads.Lite’ nuget package to the Android project, currently I’m using version 122.3.0.3
  • Amend the code in the ‘Activity.cs’ (or whatever you’ve called your Android ‘activity’ C# file) to specify the ad unit details and where to display the ad on screen

A couple of other things before we go any further… during debugging/testing you’ll want to use test ads not real ones otherwise you might get your AdMob account disabled. Luckily Google have a number of test id’s you can use for your app and any ad unit, see here. Just remember to replace them with your real AdMob app id and ad unit id when you build your production release and package it for deployment to Google Play!

time for change sign with led light
Photo by Alexas Fotos on Pexels.com

So, firstly make the following changes to your ‘AndroidManifest.xml’ file (see my example file shown below). I’ve highlighted in comment blocks (the <!– –> tags) which bits are for the AdMob stuff. The rest is just the contents of my original file for one of my games, yours may have some different values but just focus on the parts I’ve highlighted which are for required for AdMob. Obviously I’ve removed my real package and label values below (see the “YOUR VALUE HERE OBVIOUSLY” bits). Also, I’ve put one of AdMob’s test app id values in place of my games real AdMob app id…

Actually, I suppose using both a test ‘app’ id and a test ‘ad unit’ id you could (should be able to) test all this before setting up any AdMob account at all. It might be worth doing this before going through the pain of setting your AdMob account up… 😊

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="YOUR VALUE HERE OBVIOUSLY" android:versionCode="2" android:versionName="1.1">
	<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="34" />
	<uses-feature android:glEsVersion="0x00020000" android:required="true" />
	<application android:label="YOUR VALUE HERE OBVIOUSLY">
		<!-- AdMob stuff -->
		<meta-data 
			android:name="com.google.android.gms.version" 
			android:value="@integer/google_play_services_version" />		
		<meta-data
          android:name="com.google.android.gms.ads.APPLICATION_ID"
          android:value="ca-app-pub-3940256099942544~3347511713"/> <!-- One of AdMobs test app id's, use when debugging --> 
		<activity 
			android:name="com.google.android.gms.ads.AdActivity" 
			android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
	</application>
	<!-- AdMob requires these permissions -->
	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
	<uses-permission android:name="android.permission.INTERNET" />
	<uses-permission android:name="com.google.android.gms.permission.AD_ID" />
</manifest>

The last one, the ‘AD_ID’ needs to be declared otherwise you’ll get a warning/error when deploying the game to the play store. It’s about permissions regarding an advertising ID that AdMob will need for ad tracking.

Make sure if you haven’t already, add the nuget package for ‘Xamarin.GooglePlayServices.Ads.Lite’ to the Android project (I’m using version 122.3.0.3).

Now, in the Activity1.cs (or whatever name you might have changed it to) the code needs to be changed to display our ad. In short you need to create an additional ‘view’ to display the ad over your game ‘view’. I’ve put the code in between the normal boiler plate Android code you get in a Monogame Android project Activity1.cs file – see the comments below.

using Android.App;
using Android.Content.PM;
using Android.Gms.Ads;
using Android.OS;
using Android.Views;
using Android.Widget;
using JumpyKitty.Code;
using Microsoft.Xna.Framework;
using AndroidGraphics = Android.Graphics;

namespace JumpyKitty.Android
{
    [Activity(
        Label = "@string/app_name",
        MainLauncher = true,
        Icon = "@drawable/icon",
        AlwaysRetainTaskState = true,
        LaunchMode = LaunchMode.SingleInstance,
        ScreenOrientation = ScreenOrientation.Portrait,
        ConfigurationChanges = ConfigChanges.Orientation 
            | ConfigChanges.Keyboard 
            | ConfigChanges.KeyboardHidden 
            | ConfigChanges.ScreenSize
    )]
    public class GameActivity : AndroidGameActivity
    {
        private GameMain _game;
        private View _view;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Normal Monogame Android stuff
            _game = new GameMain();
            _view = _game.Services.GetService(typeof(View)) as View;

            // First create a layout to hold the ad           
            var adLayoutView = new LinearLayout(this)
            {
                Orientation = Orientation.Horizontal // Should the layout be a column or a row?
            };

            // We want to position the ad horizontally in the center of the screen, and
            // at the bottom of the screen
            adLayoutView.SetGravity(GravityFlags.CenterHorizontal | GravityFlags.Bottom);
            adLayoutView.SetBackgroundColor(AndroidGraphics.Color.Transparent);

            // Create a banner ad view. Note the test id's, for more details
            // see this link https://developers.google.com/admob/android/test-ads   
            //
            // test admob app id            = ca-app-pub-3940256099942544~3347511713
            // test admob banner ad unit id = ca-app-pub-3940256099942544/9214589741            
            var bannerAdView = new AdView(this)
            {
                AdUnitId = "ca-app-pub-3940256099942544/9214589741", // Test ad unit id for a banner
                AdSize = AdSize.Banner // We want a banner ad
            };

            // Build the banner ad view
            bannerAdView.LoadAd(new AdRequest.Builder().Build());

            // We want to always show the ad
            adLayoutView.AddView(bannerAdView);

            // Create another layout to hold the usual game view, plus our ad layout view
            var mainView = new FrameLayout(this);
            mainView.AddView(_view);
            mainView.AddView(adLayoutView);

            // Finally, set the content to use this new view
            SetContentView(mainView);

            // Run game as per normal
            _game.Run();
        }
    }
}

Once you’ve done all that, debug the game as per normal and you should hopefully see a banner ‘test ad’ at the bottom of the screen a bit like below:-

That’s it folks… good luck and hopefully it all goes well for you and remember, before publishing to production, change the test id’s to the real ones for your app and ad unit! 🫡

Update… I’ve created a Github repo for this here with a sample Monogame Android project for AdMob which displays test ads. Hope it comes in useful…

Leave a Reply

Discover more from Aventius

Subscribe now to keep reading and get access to the full archive.

Continue reading