AdMob with libGDX

Introduction

As of August 1, 2014 Google requires you to implement the Play version of the Mobile ADS SDK in your app. They offer some documentation on how to do this in Android Studio. However, we use Eclipse with the Android SDK. We also have some documentation on AdMob with libGDX. Let’s get started. This is what we did for our simple game Cave Fizzer.

Create the ad unit

Log in to AdMob. Choose ‘Monetize new app’ and pass through the steps. Picking a text banner format would be fine to get you started. You can also set up an Analytics property for this ad unit and its session here. We won’t cover that in this post. For now, you should end up with an AdMob application key.

Add the Google Play Services library

Start the Android SDK manager and make sure you have the latest version of Google Play services installed. Locate the google-play-services_lib project and copy it to wherever you want to keep your library projects. Import it into Eclipse (File->Import->Android->Existing Projects into Workspace). Check the ‘Is library’ box for this project (Properties->Android->Library). Add the library to your game’s Android project (Properties->Android->Library).

Update the manifest

You need to have these permissions in AndroidManifest.xml:

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

Set the minSdkVersion to 9.

Add this meta element to ‘application’:

<meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version"/>

Add the AdActivity:

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

Split the Views, load the game and the ads

The idea is that you have libdGDX create a View for the game, whereas the ad unit gets its own View. Then you add both to a new RelativeLayout parent. Use AdRequest.Builder to create the ad request (and to define your test device IDs).

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
 
		// Create the layout
		RelativeLayout layout = new RelativeLayout(this);
 
		// Do the stuff that initialize() would do for you
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().clearFlags(
				WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
 
		// Create the libgdx View
		View gameView = initializeForView(new CaveFizzer(this),
				new AndroidApplicationConfiguration());
 
		// Create and setup the AdMob view
		adView = new AdView(this);
		adView.setAdUnitId("ca-app-pub-................/.........."); // Put in secret key here
 
		adView.setAdSize(AdSize.SMART_BANNER);
 
		adView.setAdListener(new AdListener() {
			@Override
			public void onAdFailedToLoad(int errorCode) {
				super.onAdFailedToLoad(errorCode);
				Log.d("Admob", "Error code: " + errorCode);
				adView.loadAd(adRequest);
			}
		});
 
		adRequest = new AdRequest.Builder()
				.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
				.addTestDevice("................................")
				.addTestDevice("................................").build();
		adView.loadAd(adRequest);
 
		// Add the libgdx view
		layout.addView(gameView);
 
		// Add the AdMob view
		RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.WRAP_CONTENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
		adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
 
		layout.addView(adView, adParams);
 
		// Hook it all up
		setContentView(layout);
 
		// ...
 
}

Control ad visibility

Since you don’t want to annoy your users during game play (seriously, you shouldn’t want that), you need to be able to switch the AdView on and off from your core project. Create a Handler object member in the AndroidLauncher to accomplish that:

	private final int SHOW_ADS = 1;
	private final int HIDE_ADS = 0;
 
	protected Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SHOW_ADS: {
				adView.setVisibility(View.VISIBLE);
				break;
			}
			case HIDE_ADS: {
				adView.setVisibility(View.GONE);
				break;
			}
			}
		}
	};

Create an ActionResolver Interface in your core project.

ActionResolver.java:

package de.nitri.cavefizzer;
 
public interface ActionResolver {
	// ...
	public void showAds(boolean show);
 
}

Have the AndroidLauncher implement it:

public class AndroidLauncher extends AndroidApplication implements
		GameHelperListener, ActionResolver {
 
	// ...
 
	@Override
	public void showAds(boolean show) {
		handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
	}
}

The ActionResolver is passed to the main constructor in the core project (see above: View gameView = initializeForView(new CaveFizzer(this), new AndroidApplicationConfiguration());):

public CaveFizzer(ActionResolver actionResolver) {
	this.actionResolver = actionResolver;
}

There you have it. You can easily control the visibility of the AdView:

actionResolver.showAds(true);
actionResolver.showAds(false);

The desktop project can be fixed with a dummy resolver interface.

ActionResolverDesktop.java:

package de.nitri.cavefizzer.desktop;
 
import de.nitri.cavefizzer.ActionResolver;
 
public class ActionResolverDesktop implements ActionResolver {	
 
	// ...
 
	@Override
	public void showAds(boolean show) {		
	}
}

One thought on “AdMob with libGDX

Leave a Reply