Unity 3D: Display an AdMob banner in an existing Unity Android game scene

Tutorial on how to display an AdMob banner in an existing Unity Android project scene

Seems like using a simple Android JAR files inside a Unity Android project is not such a simple thing to do. I finally managed to get AdMob working in an existing Unity Android game. For this example I was using Unity for Windows version 3.5.2 and the latest Android plugin for Eclipse.

Prerequisites

I assume that you have a working installation of Eclipse with the Android plugin on your computer. If not, please follow this tutorial to get your workspace ready: Download the Android SDK.

The Eclipse/Android part

  • Download the AdMob JAR file and register for an account if you haven’t done so already.
  • Create a new Android project. Make sure that the namespace (the package name) is identical to the namespace of your Unity Android project. You can set the namespace in Unity through Build Settings > Player Settings > Android tab > Other Settings > „Bundle Identifier“. In my example I am using my.android.game.
  • Copy the AdMob JAR file into the /libs folder of the project (you might have to create that folder manually).
  • Search inside of your Unity installation directory for the file classes.jar. Copy this file also into the /libs folder of your Eclipse project.
  • To test if the ads are being displayed we first create a regular Android class called AdMobActivity.java. The content of this class looks like this:

    package my.android.game;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.LinearLayout;
    
    import com.admob.android.ads.AdManager;
    import com.admob.android.ads.AdView;
    import com.admob.android.ads.SimpleAdListener;
    
    public class AdMobActivity extends Activity
    {
    	@Override
    	protected void onCreate(Bundle savedInstanceState) {
    		Log.i("AdMobTest", "onCreate");
    
    		// super (UnityPlayerActivity) will use setContentView() ...
    		super.onCreate(savedInstanceState);
    
    		// ... so instead of using setContentView(), we call addContentView()
    		// from setupAds()
    		setupAds();
    
    		// Add test devices (check the logcat for the ID string of your
    		// device..)
    		// If you want to display test-ads uncomment this line of code and replace YOUR_DEVICE_ID with your device ID which AdMob displays in your logfile.
    		AdManager.setTestDevices( new String[] { "YOUR_DEVICE_ID" } );
    	}
    
    	private void setupAds() {
    		// And this is the same, but done programmatically
    		LinearLayout layout = new LinearLayout(this);
    		layout.setOrientation(LinearLayout.VERTICAL);
    		layout.setGravity(Gravity.BOTTOM);
    		addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    
    		AdView adView = new AdView(this);
    		layout.addView(adView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    
    		adView.setBackgroundColor(0xff000000);
    		adView.setPrimaryTextColor(0xffffffff);
    		adView.setSecondaryTextColor(0xffcccccc);
    		adView.setKeywords("Android game");
    		adView.setRequestInterval(15);
    
    		// add listener for easier debugging
    		adView.setAdListener(new SimpleAdListener() {
    			@Override
    			public void onFailedToReceiveAd(com.admob.android.ads.AdView adView) {
    				Log.d("AdListener", "onFailedToReceiveAd: " + adView.toString());
    				super.onFailedToReceiveAd(adView);
    			}
    
    			@Override
    			public void onFailedToReceiveRefreshedAd(com.admob.android.ads.AdView adView) {
    				Log.d("AdListener", "onFailedToReceiveRefreshedAd: " + adView.toString());
    				super.onFailedToReceiveRefreshedAd(adView);
    			}
    
    			@Override
    			public void onReceiveAd(com.admob.android.ads.AdView adView) {
    				Log.d("AdListener", "onReceiveAd: " + adView.toString());
    				super.onReceiveAd(adView);
    			}
    
    			@Override
    			public void onReceiveRefreshedAd(com.admob.android.ads.AdView adView) {
    				Log.d("AdListener", "onReceiveRefreshedAd: " + adView.toString());
    				super.onReceiveRefreshedAd(adView);
    			}
    		});
    
    		adView.requestFreshAd();
    	}
    }
    
  • Update the AndroidManifest.xml file in your Eclipse project. It should look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk android:minSdkVersion="7" />
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name="my.android.game.AdMobActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            
     		<!-- The application's publisher ID assigned by AdMob -->
            <meta-data android:value="YOUR_PUBLISHER_ID" android:name="ADMOB_PUBLISHER_ID" />
    
            <!-- AdMobActivity definition -->
            <activity android:name="com.admob.android.ads.AdMobActivity"
                      android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                      android:configChanges="orientation|keyboard|keyboardHidden" />        
    
        </application>
    
    </manifest>
    

    Make sure to replace YOUR_PUBLISHER_ID with your actual AdMob publisher ID.

  • Build and run the app on your Android phone and you should see the AdMob banner being displayed. If you don’t please refer to the AdMob tutorials how to implement the banner into the Android app. Once this works continue with this tutorial.
  • Create a class called AdMobUnityActivity.java. You can use your previously created AdMobActivity.java class as a base. The class will look like this:

    package my.android.game;
    
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Gravity;
    import android.view.ViewGroup.LayoutParams;
    import android.widget.LinearLayout;
    
    import com.admob.android.ads.AdManager;
    import com.admob.android.ads.AdView;
    import com.admob.android.ads.SimpleAdListener;
    import com.unity3d.player.UnityPlayer;
    import com.unity3d.player.UnityPlayerActivity;
    
    public class AdMobUnityActivity extends UnityPlayerActivity {
    
    	@Override
    	public void onCreate(Bundle savedInstanceState) {
    		super.onCreate(savedInstanceState);
    	}
    
    	public static void setupAdsStatic() {
    		UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    			public void run() {
    
    				// If you want to display test-ads uncomment this line of code and replace YOUR_DEVICE_ID with your device ID which AdMob displays in your logfile.
    				// AdManager.setTestDevices(new String[] { "YOUR_DEVICE_ID" });
    
    				// And this is the same, but done programmatically
    				LinearLayout layout = new LinearLayout(UnityPlayer.currentActivity.getApplicationContext());
    				layout.setOrientation(LinearLayout.VERTICAL);
    				
    				// SET HERE IF YOU WANT THE BANNER TO BE DISPLAYED AT THE TOP OR BOTTOM OF THE SCREEN
    				layout.setGravity(Gravity.BOTTOM);
    				UnityPlayer.currentActivity.addContentView(layout, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    
    				AdView adView = new AdView(UnityPlayer.currentActivity);
    				layout.addView(adView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    
    				adView.setBackgroundColor(0xff000000);
    				adView.setPrimaryTextColor(0xffffffff);
    				adView.setSecondaryTextColor(0xffcccccc);
    				
    				// SET SOME KEYWORDS FOR THE ADS TO DISPLAY
    				adView.setKeywords("Android game");
    				adView.setRequestInterval(15);
    
    				// add listener for easier debugging
    				adView.setAdListener(new SimpleAdListener() {
    					@Override
    					public void onFailedToReceiveAd(com.admob.android.ads.AdView adView) {
    						Log.d("AdListener", "onFailedToReceiveAd: " + adView.toString());
    						super.onFailedToReceiveAd(adView);
    					}
    
    					@Override
    					public void onFailedToReceiveRefreshedAd(com.admob.android.ads.AdView adView) {
    						Log.d("AdListener", "onFailedToReceiveRefreshedAd: " + adView.toString());
    						super.onFailedToReceiveRefreshedAd(adView);
    					}
    
    					@Override
    					public void onReceiveAd(com.admob.android.ads.AdView adView) {
    						Log.d("AdListener", "onReceiveAd: " + adView.toString());
    						super.onReceiveAd(adView);
    					}
    
    					@Override
    					public void onReceiveRefreshedAd(com.admob.android.ads.AdView adView) {
    						Log.d("AdListener", "onReceiveRefreshedAd: " + adView.toString());
    						super.onReceiveRefreshedAd(adView);
    					}
    				});
    
    				adView.requestFreshAd();
    			}
    
    		});
    
    	}
    }
    

    The class now extends UnityPlayerActivity instead of Activity. Also we created the static function setupAdsStatic() and left the onCreate() function nearly empty. Also we have to wrap the whole content of this function into

    UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
    	public void run() {
    		...
    	}
    }
    

    otherwise we would get an error or a crash in Unity when we call the function. Also some content inside that function is a bit different in order to make it work with Unity.

  • Not entirely sure if the following step is needed but just do it anyways: Add this line to the AndroidManifest.xml file inside the „application“ tags:
    <activity android:name="my.android.game.AdMobUnityActivity"></activity>	
    
  • Export the project to a JAR file. Click the right mouse button in the package explorer in Eclipse on your project and choose Export… > Java/JAR File > (standard settings) enter a name for the JAR file > Finish

Now you’re done with the part in Eclipse. Now we have to add that plugin into Unity 3D.

The Unity part

  • Copy the created JAR file inside your Unity Android project into the folder /Plugins/Android/
  • Also copy the AdMob JAR file into the same folder /Plugins/Android/
  • Complete the AndroidManifest.xml file inside your Unity Android project located at: \Assets\Plugins\Android\AndroidManifest.xml. The content of this file will look like this:
    <?xml version="1.0" encoding="utf-8"?>
    <manifest
        xmlns:android="http://schemas.android.com/apk/res/android"
        package="my.android.game"
    	android:installLocation="preferExternal"
        android:versionCode="1"
        android:versionName="1.0">
    	
        <supports-screens
            android:smallScreens="true"
            android:normalScreens="true"
            android:largeScreens="true"
            android:xlargeScreens="true"
            android:anyDensity="true"/>
    
        <application
    		android:icon="@drawable/app_icon"
            android:label="@string/app_name"
            android:debuggable="true">
    						
            <activity android:name="com.unity3d.player.UnityPlayerProxyActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>
            <activity android:name="com.unity3d.player.UnityPlayerNativeActivity"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
                <meta-data android:name="android.app.lib_name" android:value="unity" />
                <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
            </activity>
            <activity android:name="com.unity3d.player.VideoPlayer"
                      android:label="@string/app_name"
                      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen">
            </activity>	
    
    		<activity android:name="my.android.game.AdMobUnityActivity"></activity>	
    		
    		<!-- The application's publisher ID assigned by AdMob -->
            <meta-data android:value="YOUR_PUBLISHER_ID" android:name="ADMOB_PUBLISHER_ID" />
    
            <!-- AdMobActivity definition -->
            <activity android:name="com.admob.android.ads.AdMobActivity"
                      android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
                      android:configChanges="orientation|keyboard|keyboardHidden" />    
    
        </application>
    
    	<!-- PERMISSIONS -->
    	<uses-permission android:name="android.permission.INTERNET"></uses-permission>
    	<uses-permission android:name="android.permission.GET_TASKS"></uses-permission>
    	<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission>
    	<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    	
    </manifest>
    

    Make sure the package name (namespace) is correct and identical to the namespace in your Eclipse project. Also change the YOUR_PUBLISHER_ID value with the value of your actual AdMob publisher ID. Note that if you are already using other Android plugins this manifest file might be looking a bit different than in my example.

  • To finally display the ad banner inside a scene of your Unity Android game create or modify a C# script with the following content:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;
    using System;
    
    public class Startup : MonoBehaviour
    {
    	public static AndroidJavaClass adMobJavaClass;
    	
    	void Start() {
    		
    		if( Application.platform == RuntimePlatform.Android ) {
    			// Initialize AdMob
    			adMobJavaClass = new AndroidJavaClass("my.android.game.AdMobUnityActivity");
    			
    			// AdMob display banner
    			adMobJavaClass.CallStatic("setupAdsStatic");
    		}
    		
    	}
    }
    

    AdMob banner being displayed in Unity Android project

    The banner will now be displayed either at the top or bottom of your phone’s screen depending on what you defined in the source code in the Eclipse project. Note that this code will only be executed on an actual Android device and the banner will not show up in the Unity player! „setupAdsStatic“ has to be identical to the function name you were using inside your Eclipse project.

Well that’s all! I hope that helped you getting this nasty thing to work! Please leave your comments and questions below.

About Dominik
Currently working as an Android/iOS developer for Cineman, Switzerland. Owner of http://www.ukon.ch and https://play.google.com/store/apps/details?id=com.cheatdatabase

Comments

2 Responses to “Unity 3D: Display an AdMob banner in an existing Unity Android game scene”
  1. Damián sagt:

    Muchas gracias por la info, ahora lo voy a probar!

    Saludos!
    Damián

  2. mckiyak sagt:

    How AdMobActivity definition?com.admob.android.ads.AdMobActivity.Help please

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!

You must be logged in to post a comment.