Unity3d Android程序嵌入Admob广告条

原地址:http://dong2008hong.blog.163.com/blog/static/4696882720140441353482/

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 calledAdMobActivity.java. The content of this class looks like this:
    先决条件我假设你已经装好了Eclipse的Android插件,在您的计算机上安装。如果没有,请按照本教程,让您的工作区准备:下载Android SDK。
  • 在Eclipse/ Android的部分下载的AdMob的JAR文件,并注册一个帐号,如果你还没有这样做的话。创建一个新的Android项目。请确保您的Unity Android项目的命名空间的命名空间(包名)是相同的。您可以设置统一的命名空间中,通过Build Settings > Player Settings > Android tab > Other Settings > “Bundle Identifier”
  • 在我的例子中,我使用的my.android.game。AdMob的JAR文件复制到/libs文件夹中的项目(您可能需要手动创建该文件夹)。搜索内统一安装目录中的文件classes.jar的。把这个文件复制到/libs文件夹的Eclipse项目。如果要测试所显示的广告,我们首先创建一个普通的Android称为AdMobActivity.java的类。这一类的内容看起来像这样:
  • 以下是代码部分:
  • 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:
    更新AndroidManifest.xml 文件,像以下这样
  • <?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.

  • 将其中的YOUR_PUBLISHER_ID 替换成你的Admob发布商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.
  • 如果你没看到Admob的广告条,请按照Admob的官网教程去查看你的Admob配置步骤是否正确。
  • 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

    这个类继承了UnityPlayerActivity 。我们将创建一个静态方法setupAdsStatic().
  • 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:
    重新配置AndroidManifest.xml 文件,增加一个activity标签如下:
  • <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");
    		}
    
    	}
    }

Unity3d Android程序嵌入Admob广告条

时间: 2024-10-17 17:20:09

Unity3d Android程序嵌入Admob广告条的相关文章

如何使用PhoneGap程序将AdMob广告嵌入到你的HTML5 iOS游戏中

如果你没有AdMob账户,先注册一个AdMob账户. 点击“Monetize new app”按钮. 如果它是一个新的应用程序,你仍然要发布,选择“Add your app manually”选项卡,命名你的应用程序,在这种情况下选择platform – iOS,然后点击“Add app”选择广告形式,像你展示如何创建一个插播广告,给它命名并保存,这个过程和横幅是相同的.你应该添加他们. 写下你的广告单元ID,如果你还没有的话,就创建横幅广告类型.你应该结束有两个广告单元的ID,一个为横幅,另一

android自定义控件之滚动广告条

在一些电子商务网站上经常能够看到一些滚动的广告条,许多软件在首次使用时也有类似的广告条,如图: 其实在github上有实现这种效果的控件,不过这东西做起来也是很简单,我们今天就来看看该怎么做. 先来看看布局文件: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" and

使用Monitor调试Unity3D Android程序日志输出(非DDMS和ADB)

以往调试Android程序,一般使用Android SDK的adb命令的logcat进行命令行输出,体验比较的差. 网上搜索一般叫用DDMS,可是打开DDMS.bat批处理,会提示使用monitor.bat. 1. 在Android-SDK/tools打开Monitor.bat 2. 我是在logcat标签页那儿,新建一个过滤器,过滤指定App Name的日志输出 然后在右下角就可以看日志了~

Android自定义控件——仿淘宝、网易、彩票等广告条、Banner的制作

尊重作者劳动成果,转载时请标明该文章出自 http://blog.csdn.net/allen315410/article/details/39294343 最近翻看以前的某项目时,发现了一个极其常用的效果--广告条,或者也称不上自定义组件,但是使用频率还是相当普遍的. 打开市面上各大App主界面,或多或少会出现这样的东西,甚至一个应用中出现N多个,这种展示广告的效果,不仅动态效果好,而且众所周知的"不占屏",想想在手机设备这么小的屏幕尺寸下,能放下几页甚至十几页的广告循环播放,就知道

自定义控件(视图)28期笔记03:自定义控件之使用系统控件(广告条Viewpager)

1.首先我们看看运行效果,如下: 2. 下面就是详细实现这个效果的过程: (1)新建一个Android工程,命名为"广告条的效果",如下: (2)这里用到一个控件ViewPager,这个控件是在android-support-v4.jar(google提供扩展工具包)之中.这个包里面工具控件使用要使用全路径名声明(在Activity 或者 xml 中需要工具控件的全路径名). 在上面android-support-v4.jar下找到包android.support.v4.view中有V

【转】基于Unity3D的Android游戏添加google广告的方法——使用AdMob

前几天由于项目需要,要搞定在游戏中添加广告的方法,在U吧中搜到了这篇文章, unity3d开发的android应用中加入AD系统的具体步骤 进而获得首发出处 http://tank2308635.iteye.com/blog/1126047 从该文中找到AdMob插件的出处 AdMob plugin that works in Unity 3.2 首先尝试了同胞的方法,折腾了大概一天时间吧,未果,老是报错,最后没办法,就想,从根上解决吧,于是开始看老外的帖子,说实话英文技术贴比小说什么的好理解多

Android牟利之道(一)--界面嵌入baidu广告

终于弄清楚了Android软件界面嵌入广告的办法,以下我以嵌入baidu 广告为例小结一下:我的新浪微博:http://weibo.com/liyi200008. 过程一,下载有admob广告SDK,,admob将 baidu-android.jar 导入想要嵌入广告的的工程中.1. 右键您的工程根目录,挑选“Properties”2. 在左面板中挑选“Java Build Path”3. 然后挑选“Libraries”标签4. 点击“Add External JARs„”5. 挑选baidu-

Android Google AdMob 广告接入示例

Android Google AdMob 广告接入示例 [TOC] 首先请大家放心,虽然 Google搜索等服务被qiang了,但是 广告服务国内还是可以用的,真是普天同庆啊~~~噗! 其实这篇文章也只是记录我接入 AdMob 的过程,更具体的其实 Google 官方给的更详细(配图和视频还有GitHub 的demo 示例等),所以不想看官方(毕竟大部分英文)的可以看我写的,如果已经看了官方或者有了解了可以重点看我** 加粗 **的地方,方便你快速找到你想要的信息. Google 官方引导:ht

Google Admob广告Android全攻略1

一.登录Google AdMob中文官网:http://www.google.cn/ads/admob/   ,注册帐号. 1.点击注册AdMob帐号 2.进入Google帐号注册页面,因为要创建一个AdMob帐号,必须先要一个Google帐号 如果你已经有一个Google的话,就可以直接登录,如果没有的话,就要注册,注册很简单,成功后,会给你的注册邮箱发一个邮件. 3.进入邮箱,打开邮件的连接,会提示你帐号已经激活. 你可以在选择绑定手机,这样你的Google账户更加的安全点. 4.再次登录G