Unity3d Android app embedded in AdMob ads bar

Source: Internet
Author: User
Tags admob

Original address: http://dong2008hong.blog.163.com/blog/static/4696882720140441353482/

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

Prerequisites

I assume that there is a working installation of Eclipse with the Android plugin on your computer. If not, please follow this tutorial-Get your workspace ready: Download the Android SDK.

The eclipse/android part
  • Download the AdMob JAR file and register for a account if you haven ' t do so already.
  • Create a new Android project. Make sure, the namespace (the package name) are identical to the namespace of your Unity Android project. can set the namespace in Unity through Build Settings > Player Settings > Android tab > Other Settings &G T "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 has to create this 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 is being displayed we first create a regular Android class calledAdmobactivity.java. The content of this class looks like this:


    Prerequisite
    I assume you have installed Eclipse's Android plugin on your computer. If not, follow this tutorial to get your workspace ready: Download the Android SDK.
  • In the section of Eclipse/android
    Download the AdMob jar file and register an account if you have not yet done so.
    Create a new Android project. Make sure that the namespace of your Unity Android project namespace (package name) is the same. You can set up a unified namespace through Build Settings > Player Settings > Android tab > Other Settings > "Bundle Identifier"
  • In my case, I used the my.android.game.
    The AdMob jar files are copied to the items in the/libs folder (you may need to create the folder manually).
    Search for files within the Unified installation directory Classes.jar. Copy this file to the Eclipse project in the/libs folder.
    If you want to test the displayed ad, we first create a generic Android called Admobactivity.java class. This type of content looks like this:
  • Here is the Code section:
  • 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{@Overrideprotected void OnCreate ( Bundle savedinstancestate) {log.i ("Admobtest", "onCreate");//Super (unityplayeractivity) would 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 was the same, but did Programmaticallylinearlayout 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;//Add Listener for easier debuggingadview.setadlistener (new Simpleadlistener () {@Overridepublic void Onfailedtoreceivead ( Com.admob.android.ads.AdView AdView) {log.d ("Adlistener", "Onfailedtoreceivead:" + adview.tostring ()); Super.onfailedtoreceivead (AdView);} @Overridepublic void Onfailedtoreceiverefreshedad (Com.admob.android.ads.AdView AdView) {log.d ("Adlistener", " Onfailedtoreceiverefreshedad: "+ adview.tostring ()); Super.onfailedtoreceiverefreshedad(AdView);} @Overridepublic void Onreceivead (Com.admob.android.ads.AdView AdView) {log.d ("Adlistener", "Onreceivead:" + Adview.tostring ()); Super.onreceivead (AdView);} @Overridepublic 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 looks like this:

     

     update  androidmanifest.xml  file, such as the following 
  • <?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 an Droid:name= "Android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name= " Android.permission.ACCESS_NETWORK_STATE "/> <application android:icon=" @drawable/ic_launcher "Andro Id:label= "@string/app_name" > <activity android:name= "my.android.game.AdMobActivity" an Droid:label= "@string/app_name" > <intent-filter> <action android:name= "Android.inten T.action.main "/> <category android:name=" Android.intent.category.LAUNCHER "/> </int Ent-filter> </activity> <!--the application ' s PUBlisher ID assigned by AdMob--<meta-data android:value= "your_publisher_id" Android:name= "Admob_publisher_i D "/> <!--admobactivity definition--and <activity android:name=" Com.admob.android.ads.AdMobActiv ity "Android:theme=" @android: Style/theme.notitlebar.fullscreen "android:configchanges=" O Rientation|keyboard|keyboardhidden "/> </application></manifest>

    Make sure to replace your_publisher_id with YOUR actual AdMob PUBLISHER ID.

  • Replace the your_publisher_id with your AdMob publisher ID

  • Build and run the app on your Android phone and your should see the ADMOB banner being displayed. If you don ' t refer to the AdMob tutorials How to implement the banner into the Android app. Once This Works continue with this tutorial.
  • If you don't see AdMob's banner, follow AdMob's official website to see if your admob configuration steps are correct.
  • Create a class calledAdmobunityactivity.java. You can use your previously created Admobactivity.java class as a base. The class would 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 {@Overridepublic void onCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate);} public static void Setupadsstatic () {UnityPlayer.currentActivity.runOnUiThread (new Runnable () {public void run () {//If y ou want to display test-ads uncomment this line of code and replace your_device_id with YOUR DEVICE ID which AdMob display s in your logfile.//admanager.settestdevices (new string[] {"your_device_id"});//And this are the same, but do program Maticallylinearlayout layout = new LinearLayout (UnityPlayer.currentActivity.getApplicationContexT ()); Layout.setorientation (linearlayout.vertical);//SET here IF-want the BANNER to is DISPLAYED at the TOP OR BOTTOM of the screenlayout.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 Displayadview.setkeywords ("Android Game" ); adview.setrequestinterval;//Add listener for easier debuggingadview.setadlistener (new Simpleadlistener () {@ overridepublic void Onfailedtoreceivead (Com.admob.android.ads.AdView AdView) {log.d ("Adlistener", " Onfailedtoreceivead: "+ adview.tostring ()); Super.onfailedtoreceivead (AdView);} @Overridepublic void Onfailedtoreceiverefreshedad (com.admob.android.ads.AdView AdView) {log.d ("Adlistener", "Onfailedtoreceiverefreshedad:" + adview.tostring ()); Super.onfailedtoreceiverefreshedad (AdView);} @Overridepublic void Onreceivead (Com.admob.android.ads.AdView AdView) {log.d ("Adlistener", "Onreceivead:" + Adview.tostring ()); Super.onreceivead (AdView);} @Overridepublic 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

    This class inherits the unityplayeractivity . We will create a static method, Setupadsstatic ().
  • UnityPlayer.currentActivity.runOnUiThread (New Runnable () {public void run () {...}}

    Otherwise we would get an error or a crash in Unity if we call the function. Also Some content inside this function is a bit different in order to make it work with Unity.

  • Not entirely sure if the following step was needed but just does it anyways:add this line to the Androidmanifest.xml file in Side the "Application" Tags:
    To reconfigure the Androidmanifest.xml file, add an activity tag as follows:
  • <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 had to add the 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 theAndroidmanifest.xmlFile inside your Unity Android project located at:\assets\plugins\android\androidmanifest.xml. The content of this file would 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:versio Nname= "1.0" > <supports-screens android:smallscreens= "true" android:normalscreens= "true" Android Oid:largescreens= "true" android:xlargescreens= "true" android:anydensity= "true"/> <applicationandroi d:icon= "@drawable/app_icon" android:label= "@string/app_name" android:debuggable= "true" > <activi                  Ty 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.unity             3d.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= "@stri Ng/app_name "android:configchanges=" Fontscale|keyboard|keyboardhidden|locale|mnc|mcc|navigation|orientati On|screenlayout|screensize|smallestscreensize|uimode|touchscreen "> <meta-data android:name=" android.app.l Ib_name "android:value=" Unity "/> <meta-data android:name=" Unityplayer. Forwardnativeeventstodalvik "android:value=" true "/> </activity> <activity android:name=" Com.uni Ty3d.player.VideoPlayer "android:label=" @string/app_name "android:configchanges=" Fontsca le|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"/> <!--AdMobAc Tivity definition--<activity android:name= "Com.admob.android.ads.AdMobActivity" android:t Heme= "@android: Style/theme.notitlebar.fullscreen" android:configchanges= "Orientation|keyboard|keyboardhid Den "/> </application><!--PERMISSIONS--><uses-permission android:name=" Android.permission.INTER NET "></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) was correct and identical to the namespace in your Eclipse project. Also the your_publisher_id value with the value of YOUR actual AdMob PUBLISHER ID. Note that if you is already using other Android plugins This manifest file might is looking a bit different than in my ex Ample.

  • 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 (Applica Tion.platform = = runtimeplatform.android) {//Initialize Admobadmobjavaclass = new Androidjavaclass (" My.android.game.AdMobUnityActivity ");//AdMob Display banneradmobjavaclass.callstatic (" setupadsstatic ");}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.