关于AdMob

广告类型

一、准备工作

二、导入AdMob SDK并初始化

三、接入横幅广告(Banner Ads)

四、接入插页广告(Interstitial Ads)

五、接入激励广告(Rewarded Video Ads)

总结

后续

下篇再见。

UnityPlayerActivity.java的完整代码

【Unity与Android】02-在Unity导出的Android工程中接入Google AdMob广告-LMLPHP【Unity与Android】02-在Unity导出的Android工程中接入Google AdMob广告-LMLPHP
package com.tan.admob;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.google.android.gms.ads.reward.RewardItem;
import com.google.android.gms.ads.reward.RewardedVideoAd;
import com.google.android.gms.ads.reward.RewardedVideoAdListener;
import com.unity3d.player.*;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.print.PrintAttributes;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class UnityPlayerActivity extends Activity implements RewardedVideoAdListener {
    protected UnityPlayer mUnityPlayer; // don't change the name of this variable; referenced from native code

    //激励视频广告
    private RewardedVideoAd rewardedVideoAd;
    //激励视频广告Id
    private  String rewardVidewAdUnitId;

    // Setup activity layout
    @Override protected void onCreate(Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);

        mUnityPlayer = new UnityPlayer(this);
        setContentView(mUnityPlayer);
        mUnityPlayer.requestFocus();

        /*
        // MobileAds初始化的方法1,有监听,无法设置appId ;appId可以在AndroidManifest.xml中设置
        // AdMob Init
        MobileAds.initialize(this, new OnInitializationCompleteListener() {
            @Override
            public void onInitializationComplete(InitializationStatus initializationStatus) {
                Log.i("AdMob", "-----Admob初始化完成");
            }
        });
        */

        //MobileAds初始化的方法2,可以指定appId;当AndroidManifest中也设置了appId时,以AndroidManifest为准
        // Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713
        MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");//测试用的AppId

        //横幅(banner)广告初始化
        // Sample AdMob banner ad id: ca-app-pub-3940256099942544/6300978111
        bannerAdInit("ca-app-pub-3940256099942544/6300978111", AdSize.BANNER);

        //插页(interstitial)广告初始化
        // Sample AdMob interstitial ad id: ca-app-pub-3940256099942544/1033173712
        interstitialAdInit("ca-app-pub-3940256099942544/1033173712");

        //激励视频(Rewarded Video)广告初始化
        // Sample AdMob interstitial ad id: ca-app-pub-3940256099942544/5224354917
        rewardedVideoAdInit("ca-app-pub-3940256099942544/5224354917");
        //预加载视频
        loadRewardedVideoAd();
    }


    /**
     * banner广告初始化
     * @param adUnitId  广告id
     * @param size 广告尺寸
     */
    private  void bannerAdInit (String adUnitId, AdSize size) {
        //创建广告视图
        AdView bannerAdView = new AdView(this);
        //设置广告尺寸
        bannerAdView.setAdSize(size);
        //设置广告ID
        bannerAdView.setAdUnitId(adUnitId);
        //请求广告
        AdRequest adRequest = new AdRequest.Builder().build();
        bannerAdView.loadAd(adRequest);
        //添加监听
        bannerAdView.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                Log.i("BannerAd", "banner广告加载完成");
            }

            @Override
            public void onAdFailedToLoad(int errCode) {
                Log.i("BannerAd", "banner广告加载失败, err_code:" + errCode);
            }

            @Override
            public void onAdOpened() {
                Log.i("BannerAd", "banner广告被打开");
            }
        });

        //声明一个布局参数(MATCH_PARENT为填充父级,WRAP_CONTENT为包裹内容)
        FrameLayout.LayoutParams fllp = new FrameLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);

        //设置布局对齐方式为:垂直对齐到底,水平居中
        fllp.gravity = Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL;

        //添加到View
        addContentView(bannerAdView, fllp);
    }

    /**
     * 插页广告初始化
     * @param adUnitId 广告id
     */
    private void interstitialAdInit (String adUnitId) {
        InterstitialAd interstitialAd = new InterstitialAd(this);

        interstitialAd.setAdUnitId(adUnitId);

        interstitialAd.loadAd(new AdRequest.Builder().build());

        Log.i("interstitalAd", "is Loaded:" + interstitialAd.isLoaded());

        interstitialAd.setAdListener(new AdListener() {
            @Override
            public void onAdClosed() {
                super.onAdClosed();
                Log.i("interstitalAd", "插页广告被关闭");

                // Load the next interstitial.
                //interstitialAd.loadAd(new AdRequest.Builder().build());
           }

            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                Log.i("interstitalAd", "插页广告加载完成");

                interstitialAd.show();
            }
        });
    }

    /**
     * 激励视频(Rewarded Video)广告初始化
     */
    private void rewardedVideoAdInit (String adUnitId) {
        // Use an activity context to get the rewarded video instance.
        rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);

        rewardedVideoAd.setRewardedVideoAdListener(this);

        rewardVidewAdUnitId = adUnitId;
    }

    //加载激励视频
    private void loadRewardedVideoAd() {
        rewardedVideoAd.loadAd(rewardVidewAdUnitId, new AdRequest.Builder().build());
    }

    //显示激励视频
    public void showRewardedVideoAd() {
        if (rewardedVideoAd.isLoaded()) {
            rewardedVideoAd.show();
        } else {
            Toast.makeText(this, "video is not ready.", Toast.LENGTH_SHORT);
        }
    }

    @Override protected void onNewIntent(Intent intent)
    {
        // To support deep linking, we need to make sure that the client can get access to
        // the last sent intent. The clients access this through a JNI api that allows them
        // to get the intent set on launch. To update that after launch we have to manually
        // replace the intent with the one caught here.
        setIntent(intent);
    }

    // Quit Unity
    @Override protected void onDestroy ()
    {
        mUnityPlayer.destroy();
        super.onDestroy();
    }

    // Pause Unity
    @Override protected void onPause()
    {
        super.onPause();
        mUnityPlayer.pause();
    }

    // Resume Unity
    @Override protected void onResume()
    {
        super.onResume();
        mUnityPlayer.resume();
    }

    @Override protected void onStart()
    {
        super.onStart();
        mUnityPlayer.start();
    }

    @Override protected void onStop()
    {
        super.onStop();
        mUnityPlayer.stop();
    }

    // Low Memory Unity
    @Override public void onLowMemory()
    {
        super.onLowMemory();
        mUnityPlayer.lowMemory();
    }

    // Trim Memory Unity
    @Override public void onTrimMemory(int level)
    {
        super.onTrimMemory(level);
        if (level == TRIM_MEMORY_RUNNING_CRITICAL)
        {
            mUnityPlayer.lowMemory();
        }
    }

    // This ensures the layout will be correct.
    @Override public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);
        mUnityPlayer.configurationChanged(newConfig);
    }

    // Notify Unity of the focus change.
    @Override public void onWindowFocusChanged(boolean hasFocus)
    {
        super.onWindowFocusChanged(hasFocus);
        mUnityPlayer.windowFocusChanged(hasFocus);
    }

    // For some reason the multiple keyevent type is not supported by the ndk.
    // Force event injection by overriding dispatchKeyEvent().
    @Override public boolean dispatchKeyEvent(KeyEvent event)
    {
        if (event.getAction() == KeyEvent.ACTION_MULTIPLE)
            return mUnityPlayer.injectEvent(event);
        return super.dispatchKeyEvent(event);
    }

    // Pass any events not handled by (unfocused) views straight to UnityPlayer
    @Override public boolean onKeyUp(int keyCode, KeyEvent event)     { return mUnityPlayer.injectEvent(event); }
    @Override public boolean onKeyDown(int keyCode, KeyEvent event)   { return mUnityPlayer.injectEvent(event); }
    @Override public boolean onTouchEvent(MotionEvent event)          { return mUnityPlayer.injectEvent(event); }
    /*API12*/ public boolean onGenericMotionEvent(MotionEvent event)  { return mUnityPlayer.injectEvent(event); }


    /**---------------激励视频监听实现 begin-------------------*/
    @Override
    public void onRewardedVideoAdLoaded() {
        Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
        showRewardedVideoAd();
    }

    @Override
    public void onRewardedVideoAdOpened() {
        Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRewardedVideoStarted() {
        Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRewardedVideoAdClosed() {
        Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();

        // Load the next rewarded video ad.
        loadRewardedVideoAd();
    }

    @Override
    public void onRewarded(RewardItem reward) {
        Toast.makeText(this, "onRewarded! currency: " + reward.getType() + "  amount: " +
                reward.getAmount(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRewardedVideoAdLeftApplication() {
        Toast.makeText(this, "onRewardedVideoAdLeftApplication",
                Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRewardedVideoAdFailedToLoad(int i) {
        Toast.makeText(this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRewardedVideoCompleted() {
        Toast.makeText(this, "onRewardedVideoCompleted", Toast.LENGTH_SHORT).show();
    }
    /**---------------激励视频监听实现 end-------------------*/

}
View Code

build.gradle

【Unity与Android】02-在Unity导出的Android工程中接入Google AdMob广告-LMLPHP【Unity与Android】02-在Unity导出的Android工程中接入Google AdMob广告-LMLPHP
// GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAIN

buildscript {
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
}
}

allprojects {
    repositories {
        google()
        jcenter()
        flatDir {
            dirs 'libs'
        }
    }
}

apply plugin: 'com.android.application'


dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.android.gms:play-services-ads:18.2.0'
}

android {
    compileSdkVersion 29
    buildToolsVersion '29.0.2'

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 29
        applicationId 'com.tan.admob'
        ndk {
            abiFilters 'armeabi-v7a', 'x86'
        }
        versionCode 1
        versionName '0.1'
    }

    lintOptions {
        abortOnError false
    }

    aaptOptions {
        noCompress = ['.unity3d', '.ress', '.resource', '.obb']
    }

    buildTypes {
        debug {
            minifyEnabled false
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'
            jniDebuggable true
        }
        release {
            minifyEnabled false
            useProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-unity.txt'
            signingConfig signingConfigs.debug
        }
    }

    packagingOptions {
        doNotStrip '*/armeabi-v7a/*.so'
        doNotStrip '*/x86/*.so'
    }

    bundle {
        language {
            enableSplit = false
        }
        density {
            enableSplit = false
        }
        abi {
            enableSplit = true
        }
    }
}
View Code

AndroidManifest.xml

【Unity与Android】02-在Unity导出的Android工程中接入Google AdMob广告-LMLPHP【Unity与Android】02-在Unity导出的Android工程中接入Google AdMob广告-LMLPHP
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tan.admob" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal">
  <supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" />
  <application android:theme="@style/UnityThemeSelector" android:icon="@mipmap/app_icon" android:label="@string/app_name" android:isGame="true" android:banner="@drawable/app_banner">
    <activity android:label="@string/app_name" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale|layoutDirection|density" android:hardwareAccelerated="false" android:name="com.tan.admob.UnityPlayerActivity">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
        <category android:name="android.intent.category.LEANBACK_LAUNCHER" />
      </intent-filter>
      <meta-data android:name="unityplayer.UnityActivity" android:value="true" />
    </activity>
    <meta-data android:name="unity.build-id" android:value="fea8e2f2-427d-4c46-a8ec-f06bef433231" />
    <meta-data android:name="unity.splash-mode" android:value="0" />
    <meta-data android:name="unity.splash-enable" android:value="True" />

    <!-- Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 -->
    <meta-data
        android:name="com.google.android.gms.ads.APPLICATION_ID"
        android:value="ca-app-pub-3940256099942544~3347511713"/>

  </application>
  <uses-feature android:glEsVersion="0x00020000" />
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-feature android:name="android.hardware.touchscreen" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch" android:required="false" />
  <uses-feature android:name="android.hardware.touchscreen.multitouch.distinct" android:required="false" />
</manifest>
View Code
10-07 04:16