Unity3D游戏接入小米广告SDK

此文章只讲Unity与Android核心交互代码
详细接入可参考小米广告 SDK Android 集成指南

小米广告常用有四种,1.开屏广告、2.Banner横幅广告、3.插屏广告、4.激励视频广告。
其中开屏广告无需代码调用,广告后台配置是否展示即可,所以本文讲述后面三种广告类型的调用过程。

Unity端调用广告SDK接口

using UnityEngine;
public class AndroidPlatformUtil : MonoBehaviour
{
    static AndroidPlatformUtil _instance;
    public static AndroidPlatformUtil instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject obj = new GameObject();
                Debug.Log("产生一个AndroidPlatformUtil");
                obj.name = "AndroidPlatformUtil";
                _instance = obj.AddComponent<AndroidPlatformUtil>();
                DontDestroyOnLoad(_instance.gameObject);
            }
            return _instance;
        }
    }
    
    public void Init(string config)
    {
        Debug.LogError("手机初始化...");
    }

    /// <summary>
    /// Android主Player
    /// </summary>
    public const string S_MainPlayer = "com.unity3d.player.UnityPlayer";
    /// <summary>
    /// Android主Activity
    /// </summary>
    public const string S_MainAct = "currentActivity";
    
    private AndroidJavaObject javaObject = null;

    public void CallAD(string methodName)
    {
        using (AndroidJavaClass jc = new AndroidJavaClass(S_MainPlayer))
        {
            using (AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>(S_MainAct))
            {
                javaObject = new AndroidJavaObject("com.game.mi.MainActivity");
                javaObject.Call(methodName, jo);
            }
        }
    }
    
	public void CallInitAd()
    {
        CallAD("Init");
    }
    
    public void CallBannerAd()
    {
        CallAD("CallBannerAd");
    }

    public void CallInterstialAd()
    {
        CallAD("CallInterstialAd");
    }

    public void CallVedioRewardAd()
    {
        CallAD("CallVedioRewardAd");
    }
    
	public void CallBackVedioRewardAd(string callBackArg)
    {
    	//激励视频广告回调,做奖励处理
    }

Android端调起广告方法
步骤一
1.Application中初始化广告SDK。
2.定义一个Handler,作用:使banner广告和插屏广告运行在游戏线程中,从而不会打断游戏正常运行。

package com.game.mi;

import com.miui.zeus.mimo.sdk.MimoSdk;
import com.miui.zeus.mimo.sdk.api.IMimoSdkListener;
import android.Manifest;
import android.app.Application;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.Toast;
import com.game.mi.R;

/**
 * 您可以参考本类中的代码来接入小米游戏广告SDK。在接入过程中,有如下事项需要注意:
 * 1.请将 APP_ID 值替换成您在小米开发者网站上申请的 AppID。
 */
public class AdApplication extends Application {
    // 请注意,千万要把以下的 APP_ID 替换成您在小米开发者网站上申请的 AppID。否则,可能会影响你的应用广告收益。
    private static final String APP_ID = "广告后台申请的APPID";
    // 以下两个没有的话就按照以下传入
    private static final String APP_KEY = "fake_app_key";
    private static final String APP_TOKEN = "fake_app_token";
    //
    public static Handler handler;

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler();
        // 如果担心sdk自升级会影响开发者自身app的稳定性可以关闭,
        // 但是这也意味着您必须得重新发版才能使用最新版本的sdk, 建议开启自升级
        // MimoSdk.setEnableUpdate(false);

        // 正式上线时候务必关闭stage和debug
//        MimoSdk.setDebugOn();
//        MimoSdk.setStageOn();

        // 如需要在本地预置插件,请在assets目录下添加mimo_asset.apk;
        MimoSdk.init(this, APP_ID, APP_KEY, APP_TOKEN, new IMimoSdkListener() {
            @Override
            public void onSdkInitSuccess() {
//                Toast.makeText(AdApplication.this, R.string.sdk_is_ready, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onSdkInitFailed() {
//                Toast.makeText(AdApplication.this, R.string.sdk_is_failed, Toast.LENGTH_LONG).show();
            }
        });
    }

}

步骤二
Android端提供给Unity的接口

package com.game.mi;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.widget.Toast;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;

public class MainActivity extends UnityPlayerActivity {

    private static MainActivity _instance;
    public static MainActivity instance()
    {
        if(null == _instance)
            _instance = new MainActivity();
        return _instance;
    }

    public Context context;

    //初始化权限
    public void Init(Object obj){
        _unityActivity= (Activity) obj; //游戏当前activity
        context=(Context) obj;
        // 如果api >= 23 需要显式申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            if (ContextCompat.checkSelfPermission(context,Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(get_unityActivity(),new String[]{Manifest.permission.READ_PHONE_STATE}     , 0);
            }
        }
    }

    //banner广告
    public void CallBannerAd(Object obj){
        _unityActivity= (Activity) obj; 
        context=(Context) obj;
        BannerActivity.instance().Show(get_unityActivity());
    }

    //插屏广告
    public void CallInterstialAd(Object obj){
        _unityActivity= (Activity) obj;
        context=(Context) obj;
        VerticalInterstitialActivity.instance().Show(get_unityActivity(),context);
    }

    //视频广告
    public void CallVedioRewardAd(Object obj){
        context=(Context) obj;
        Intent intent = new Intent(context, RewardVideoDemoActivity.class);
        context.startActivity(intent);
    }

    //游戏退出桌面关闭Banner
    public void OnApplicationPause(Object obj){
        _unityActivity= (Activity) obj;
        context=(Context) obj;
        BannerActivity.instance().dismiss();
    }

    //Unity回调视频奖励
    public void CallBackVedioRewardAd(){
        UnityPlayer.UnitySendMessage("MobileController", "VedioReward","callback");
    }

    private Activity _unityActivity;
    Activity get_unityActivity() {
        if (null == _unityActivity) {
            try {
                Class<?> classtype = Class.forName("com.unity3d.player.UnityPlayer");
                Activity activity = (Activity) classtype.getDeclaredField("currentActivity").get(classtype);
                _unityActivity = activity;
            } catch (ClassNotFoundException e) {

            } catch (IllegalAccessException e) {

            } catch (NoSuchFieldException e) {

            }
        }
        return _unityActivity;
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        return super.dispatchKeyEvent(event);
    }
}

步骤三
激励视频广告直接启动Activity即可完成广告请求,Banner广告和插屏广告需要特殊处理,让广告能够不影响游戏正常运行。

Banner广告
1.创建一个View,可以理解为用来装banner广告的一个容器。
2.WindowManager,可以理解为设置这个容器的参数,显示位置、长宽。
3.步骤一声明的handler在此处使用。

package com.game.mi;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.miui.zeus.mimo.sdk.ad.AdWorkerFactory;
import com.miui.zeus.mimo.sdk.ad.IAdWorker;
import com.miui.zeus.mimo.sdk.listener.MimoAdListener;
import com.xiaomi.ad.common.pojo.AdType;

public class BannerActivity extends Activity {
    private static final String BANNER_POS_ID = "Banner广告位ID";

    private static BannerActivity _instance;
    public static BannerActivity instance()
    {
        if(null == _instance)
            _instance = new BannerActivity();
        return _instance;
    }

    IAdWorker mBannerAd;
    private  Activity activity;
    private WindowManager mWindowManager;
    private FrameLayout bannerContainer;
    private View mLayout;
    private boolean added;

    public void Show(Activity _activity) {
        if (added) return;
        activity=_activity;
        FrameLayout layout = new FrameLayout(activity);
        mLayout = layout;
        bannerContainer = layout;
        //获取WindowManager
        mWindowManager=activity.getWindowManager();
        final WindowManager.LayoutParams param = new WindowManager.LayoutParams();
        param.gravity = Gravity.BOTTOM | Gravity.CENTER;
        param.type = WindowManager.LayoutParams.TYPE_APPLICATION;
        param.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
        param.alpha = 1.0f;
        param.width = WindowManager.LayoutParams.FILL_PARENT;
        param.height = 180;
        param.format = PixelFormat.RGBA_8888;

        AdApplication.handler.post(new Runnable() {
            public void run() {
                //创建出的广告view加入WindowManager
                mWindowManager.addView(mLayout, param);

                try{
                    mBannerAd = AdWorkerFactory.getAdWorker(activity, bannerContainer, new MimoAdListener() {
                        @Override
                        public void onAdPresent() {
                            //                    Toast.makeText(activity, "Banner广告展示成功",
                            //                            Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onAdClick() {

                        }

                        @Override
                        public void onAdDismissed() {
                            //                    Toast.makeText(activity, "Banner广告消失",
                            //                            Toast.LENGTH_LONG).show();
                            dismiss();
                        }

                        @Override
                        public void onAdFailed(String s) {
                            //                    Toast.makeText(activity, "Banner广告加载失败:" + s,
                            //                            Toast.LENGTH_LONG).show();
                            dismiss();
                        }

                        @Override
                        public void onAdLoaded(int size) {
                            //                    Toast.makeText(activity, "Banner广告加载成功",
                            //                            Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onStimulateSuccess() {
                        }
                    }, AdType.AD_BANNER);
                }catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    mBannerAd.loadAndShow(BANNER_POS_ID);
                    added=true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void dismiss() {
        try {
            if (added) {
                mWindowManager.removeView(mLayout);
                added = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        try{
            super.onDestroy();
            dismiss();
            mBannerAd.recycle();
        }catch (Exception e) {
        }
    }
}

插屏广告
1.步骤一声明的handler在此处使用。

package com.game.mi;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.ViewGroup;
import com.miui.zeus.mimo.sdk.ad.AdWorkerFactory;
import com.miui.zeus.mimo.sdk.ad.IAdWorker;
import com.miui.zeus.mimo.sdk.listener.MimoAdListener;
import com.xiaomi.ad.common.pojo.AdType;
import android.widget.Toast;

public class VerticalInterstitialActivity extends Activity {
    public static final String TAG = "VerticalInterstitial";
    //以下的POSITION_ID 需要使用您申请的值替换下面内容
    private static final String POSITION_ID = "插屏广告位ID";
    
	private IAdWorker mAdWorker;
    private  Activity activity;
    private  Context context;
    private boolean added;

    private static VerticalInterstitialActivity _instance;
    public static VerticalInterstitialActivity instance()
    {
        if(null == _instance)
            _instance = new VerticalInterstitialActivity();
        return _instance;
    }
    
    public void Show(Activity _activity, Context _context) {
        if (added) return;
        activity = _activity;
        context=_context;
        AdApplication.handler.post(new Runnable() {
            public void run() {
                //在这里,mPlayBtn是作为一个锚点传入的,可以换成任意其他的view,比如getWindow().getDecorView()
                try {
                    mAdWorker = AdWorkerFactory.getAdWorker(context, (ViewGroup) activity.getWindow().getDecorView(), new MimoAdListener() {
                        @Override
                        public void onAdPresent() {
                            Log.e(TAG, "onAdPresent");
//                            Toast.makeText(activity, "插屏广告展示成功",
//                                    Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onAdClick() {
                            Log.e(TAG, "onAdClick");
                        }

                        @Override
                        public void onAdDismissed() {
                            Log.e(TAG, "onAdDismissed");
                            dismiss();
//                            Toast.makeText(activity, "插屏广告消失",
//                                    Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onAdFailed(String s) {
                            Log.e(TAG, "onAdFailed");
                            dismiss();
//                            Toast.makeText(activity, "插屏广告加载失败:" + s,
//                                    Toast.LENGTH_LONG).show();
                        }

                        @Override
                        public void onAdLoaded(int size) {
//                            Toast.makeText(activity, "插屏广告加载成功",
//                                    Toast.LENGTH_LONG).show();
                            Log.e(TAG, "ad loaded");
                            ShowAd();
                        }

                        @Override
                        public void onStimulateSuccess() {
                        }
                    }, AdType.AD_INTERSTITIAL);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                try {
                    if (!mAdWorker.isReady()) {
                        mAdWorker.load(POSITION_ID);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }

    public void ShowAd(){
        try {
            if (mAdWorker.isReady()) {
                mAdWorker.show();
                added=true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void dismiss() {
        try {
            if (added) {
                mAdWorker.recycle();
                added = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        try {
            super.onDestroy();
            dismiss();
        } catch (Exception e) {
        }
    }
}
展开阅读全文
©️2020 CSDN 皮肤主题: 游动-白 设计师: 上身试试 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值