unity接入华为huawei 广告,分析,远程配置等功能

因为华为没有直接给unity调的SDK,要用到android写一个aar的插件给unity来调用
1.AndroidMainfest.xml 这里要配置的内容

    
    
    
    
    

2.然后新建一个HuaWeiManager空物体把HuaWeiManager.cs 这个脚本要接受到android的回调的话必须要放在场景上面挂着

using System.Collections;
using System.Collections.Generic;
using QFramework;
using UnityEngine;

#if UNITY_ANDROID&&huawei
public class HuaWeiManager : MonoSingleton {
    AndroidJavaClass jc;
    AndroidJavaObject jo;

    void Start()
    {
        jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
        jo = jc.GetStatic("currentActivity");
    }

    /// 
    /// 发送事件
    /// 
    /// 
    public void HW_LogEvent(string strEvent) {
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAgconnectHelper");
        if (javaClass != null) {
            if(jc==null)jc= new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if(jo==null)jo= jc.GetStatic("currentActivity");
            javaClass.CallStatic("logEvent", jo,strEvent);
        } else {
            Debug.Log("=====HW_LogEvent==null====");
        }
    }

    /// 
    /// 远程配置
    /// 
    /// 
    public string HW_RemoteStringValue(string strKey) {
        Debug.Log("======HwAgconnectHelper.HW_RemoteStringValue======" + strKey);
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAgconnectHelper");
        if (javaClass != null) {
            if (jc == null) jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (jo == null) jo = jc.GetStatic("currentActivity");
            string str= javaClass.CallStatic("getRemoteStringValue", strKey);
            Debug.Log("===HW_RemoteStringValue.key=" +strKey+"  =value=="+str);
            return str;
        } else {
            Debug.Log("=====HW_RemoteStringValue==null====");
            return null;
        }
    }

    public void InitHuiwei() {
        Debug.Log("===HuaWeiManager===InitHuiwei======");
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAdHelperJava");
        if (javaClass != null) {
            if (jc == null) jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (jo == null) jo = jc.GetStatic("currentActivity");
            javaClass.CallStatic("init", jo,true);
        } else {
            Debug.Log("=====InitHuiwei==null====");
        }
    }

    public void LoadRewardAd() {
        Debug.Log("====HuaWeiManager==ShowReward======");
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAdHelperJava");
        if (javaClass != null) {
            if (jc == null) jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (jo == null) jo = jc.GetStatic("currentActivity");
            javaClass.CallStatic("loadRewardAd");
        } else {
            Debug.Log("=====ShowReward==null====");
        }
    }

    public void ShowRewardAd() {
        Debug.Log("====HuaWeiManager==ShowReward======");
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAdHelperJava");
        if (javaClass != null) {
            if (jc == null) jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (jo == null) jo = jc.GetStatic("currentActivity");
            javaClass.CallStatic("showRewardAd");
        } else {
            Debug.Log("=====ShowReward==null====");
        }
    }

    public void ShowBanner() {
        Debug.Log("====HuaWeiManager==ShowBanner======");
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAdHelperJava");
        if (javaClass != null) {
            if (jc == null) jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (jo == null) jo = jc.GetStatic("currentActivity");
            javaClass.CallStatic("showBanner", jo, 2);
        } else {
            Debug.Log("=====ShowBanner==null====");
        }
    }

    public void HideBanner() {
        Debug.Log("===HuaWeiManager===HideBanner======");
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAdHelperJava");
        if (javaClass != null) {
            if (jc == null) jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (jo == null) jo = jc.GetStatic("currentActivity");
            javaClass.CallStatic("dismissBanner");
        } else {
            Debug.Log("=====HideBanner==null====");
        }
    }

    public void LoadInterstitialAd() {
        Debug.Log("===HuaWeiManager===loadInterstitialAd======");
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAdHelperJava");
        if (javaClass != null) {
            if (jc == null) jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (jo == null) jo = jc.GetStatic("currentActivity");
            javaClass.CallStatic("loadInterstitialAd");
        } else {
            Debug.Log("=====loadInterstitialAd==null====");
        }
    }

    public void ShowInterstitial() {
        Debug.Log("===HuaWeiManager===ShowInterstitial======");
        AndroidJavaObject javaClass = new AndroidJavaObject("com.cocos.adsdk.java.HwAdHelperJava");
        if (javaClass != null) {
            if (jc == null) jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
            if (jo == null) jo = jc.GetStatic("currentActivity");
            javaClass.CallStatic("showInterstitialAd");
        } else {
            Debug.Log("=====ShowInterstitial==null====");
        }
    }

    /// 
    /// 广告获取成功时调用banner
    /// 
    public void onAdLoaded_banner_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdLoaded_banner_callback===");
    }

    /// 
    /// 广告获取失败时调用banner
    /// 
    /// 
    public void onAdFailed_banner_callback(string errorCode) {
        Debug.Log("===HuaWeiManager.onAdFailed_banner_callback==="+errorCode);

    }

    /// 
    /// 广告打开时调用banner
    /// 
    public void onAdOpened_banner_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdOpened_banner_callback===");

    }

    /// 
    /// 广告点击时调用banner
    /// 
    public void onAdClicked_banner_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdClicked_banner_callback===");

    }

    /// 
    /// 广告关闭时调用banner
    /// 
    public void onAdClosed_banner_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdClosed_banner_callback===");

    }

    /// 
    /// 广告获取成功时调用interstitial
    /// 
    public void onAdLoaded_interstitial_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdLoaded_interstitial_callback===");

    }

    /// 
    /// 广告获取失败时调用interstitial
    /// 
    /// 
    public void onAdFailed_interstitial_callback(string errorCode) {
        Debug.Log("===HuaWeiManager.onAdFailed_interstitial_callback==="+ errorCode);

    }

    /// 
    /// 广告打开时调用interstitial
    /// 
    public void onAdOpened_interstitial_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdOpened_interstitial_callback===");

    }

    /// 
    /// 广告点击时调用interstitial
    /// 
    public void onAdClicked_interstitial_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdClicked_interstitial_callback===");

    }

    /// 
    /// 广告关闭时调用interstitial
    /// 
    public void onAdClosed_interstitial_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdClosed_interstitial_callback===");

    }

    /// 
    /// 广告离开时调用interstitial
    /// 
    public void onAdLeave_interstitial_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdLeave_interstitial_callback===");

    }

    /// 
    ///  广告曝光时调用interstitial
    /// 
    public void onAdImpression_interstitial_callback(string str) {
        Debug.Log("===HuaWeiManager.onAdImpression_interstitial_callback===");

    }

    /// 
    /// 广告获取失败时调用reward
    /// 
    /// 
    public void onRewardAdFailedToShow_rewardAd_callback(string errorCode) {
        Debug.Log("===HuaWeiManager.onRewardAdFailedToShow_rewardAd_callback===" + errorCode);

    }

    /// 
    /// 广告打开时调用reward
    /// 
    public void onRewardAdOpened_rewardAd_callback(string str) {
        Debug.Log("===HuaWeiManager.onRewardAdOpened_rewardAd_callback===");

    }

    /// 
    /// 广告关闭时调用reward
    /// 
    public void onRewardAdClosed_rewardAd_callback(string str) {
        Debug.Log("===HuaWeiManager.onRewardAdClosed_rewardAd_callback===");

    }

    /// 
    /// 激励广告奖励达成,发放奖励reward
    /// 
    public void onRewarded_rewardAd_callback(string str) {
        Debug.Log("===HuaWeiManager.onRewarded_rewardAd_callback===");

    }


    //void OnGUI() {
    //    if (GUI.Button(new Rect(500,800,150,150), "ShowReward")) {

    //        ShowRewardAd();
    //    }
    //}
}
#endif

3.再然后就是配置gradle文件了

buildscript {
    ext.kotlin_version = "1.3.72" //huawei
    repositories {
        mavenCentral()
        google()
        jcenter()
        maven {url 'https://developer.huawei.com/repo/'} //huawei
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.0'
        classpath 'com.huawei.agconnect:agcp:1.5.2.300' //huawei
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" //huawei
        classpath 'com.huawei.agconnect:agconnect-apms-plugin:1.4.1.306'
**BUILD_SCRIPT_DEPS**}
}
allprojects {
    repositories {
        mavenCentral()
        google()
        jcenter()
        maven {url 'https://developer.huawei.com/repo/'} //huawei
        flatDir {
            dirs 'libs'
        }
    }
}

// Android Resolver Repos End
apply plugin: 'com.android.application'
//huiwei
apply plugin: 'com.huawei.agconnect'
apply plugin: 'kotlin-android'
apply plugin: 'com.huawei.agconnect.apms'

dependencies {
    //huawei setting
    implementation 'com.huawei.agconnect:agconnect-core:1.5.2.300' // huawei
    implementation 'com.huawei.agconnect:agconnect-remoteconfig:1.5.2.300'
    implementation 'com.huawei.agconnect:agconnect-crash:1.5.2.300'
    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation (name:'huaweiSDK',ext:'aar') //这个就是安桌那边写出来的AAR引用的库
    implementation 'com.huawei.hms:ads-lite:13.4.41.304'
    implementation 'com.huawei.hms:ads-identifier:3.4.39.302'
    implementation 'com.huawei.hms:ads-installreferrer:3.4.39.302'
    implementation 'com.huawei.agconnect:agconnect-apms:1.4.1.306'
}

//这里主要是为了把华为的json文件放在应用的根目录,然后我们unity对应的目录不知道在哪里面,所以就用这个方法来复制到根目录下。
task copyJsonFile{
    copy{
        delete("agconnect-services.json")
        delete("keystore文件")
        from('build/huawei/android') //从这个目录复制一份出来
        into('./')   //然后放到这个目录下面
        include("agconnect-services.json")
        include("keystore文件")
    }
}

现在unity这边干的事已经完成了剩下的就是android这边写的插件了
4.android HwAdHelperJava 的脚本

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.cocos.adsdk.java;

import android.app.Activity;
import android.content.Intent;
import android.os.RemoteException;
import android.util.Log;
import com.cocos.adsdk.core.HwAdHelper;
import com.cocos.adsdk.core.openad.SplashActivity;
import com.google.android.gms.ads.identifier.AdvertisingIdClient;
import com.google.android.gms.ads.identifier.AdvertisingIdClient.Info;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.huawei.hms.ads.installreferrer.api.InstallReferrerClient;
import com.huawei.hms.ads.installreferrer.api.InstallReferrerStateListener;
import com.huawei.hms.ads.installreferrer.api.ReferrerDetails;
import java.io.IOException;

public class HwAdHelperJava {
    private static final String TAG = "HwAdHelperJava";
    private static InstallReferrerClient mReferrerClient;
    private static InstallReferrerStateListener installReferrerStateListener = new InstallReferrerStateListener() {
        public void onInstallReferrerSetupFinished(int responseCode) {
            switch(responseCode) {
            case 0:
                Log.i("HwAdHelperJava", "connect ads kit ok");

                try {
                    ReferrerDetails var2 = HwAdHelperJava.mReferrerClient.getInstallReferrer();
                } catch (RemoteException var3) {
                    Log.i("HwAdHelperJava", "getInstallReferrer RemoteException: " + var3.getMessage());
                } catch (IOException var4) {
                    Log.i("HwAdHelperJava", "getInstallReferrer IOException: " + var4.getMessage());
                }
                break;
            case 1:
                Log.i("HwAdHelperJava", "SERVICE_UNAVAILABLE");
                break;
            case 2:
                Log.i("HwAdHelperJava", "FEATURE_NOT_SUPPORTED");
                break;
            default:
                Log.i("HwAdHelperJava", "responseCode: " + responseCode);
            }

        }

        public void onInstallReferrerServiceDisconnected() {
            Log.i("HwAdHelperJava", "onInstallReferrerServiceDisconnected");
        }
    };

    public HwAdHelperJava() {
    }

    public static void init(Activity activity, boolean isTest) {
        HwAdHelper.INSTANCE.init(activity, isTest);
        getOAID(activity);
        initReferrerClient(activity);
    }

    public static void openSplashActivity(Activity activity) {
        Intent intent = new Intent(activity, SplashActivity.class);
        activity.startActivity(intent);
    }

    private static void initReferrerClient(final Activity activity) {
        (new Thread() {
            public void run() {
                HwAdHelperJava.mReferrerClient = InstallReferrerClient.newBuilder(activity).build();
                HwAdHelperJava.mReferrerClient.startConnection(HwAdHelperJava.installReferrerStateListener);
            }
        }).start();
    }

    public static void showBanner(Activity activity, int position) {
        HwAdHelper.INSTANCE.showBanner(activity, position);
    }

    private static void getOAID(final Activity activity) {
        (new Thread() {
            public void run() {
                try {
                    Info info = AdvertisingIdClient.getAdvertisingIdInfo(activity.getApplicationContext());
                    if (null != info) {
                        Log.i("TAG", "getAdvertisingIdInfo id=" + info.getId() + ", isLimitAdTrackingEnabled=" + info.isLimitAdTrackingEnabled());
                    }
                } catch (IOException var2) {
                    Log.i("TAG", "getAdvertisingIdInfo Exception: " + var2.toString());
                } catch (GooglePlayServicesNotAvailableException var3) {
                    var3.printStackTrace();
                } catch (GooglePlayServicesRepairableException var4) {
                    var4.printStackTrace();
                }

            }
        }).start();
    }

    public static void showInterstitialAd() {
        HwAdHelper.INSTANCE.showInterstitialAd();
    }

    public static void showRewardAd() {
        HwAdHelper.INSTANCE.showRewardAd();
    }

    public static void loadRewardAd() {
        HwAdHelper.INSTANCE.loadRewardAd();
    }

    public static boolean isRewardAdReady() {
        return HwAdHelper.INSTANCE.isRewardAdReady();
    }

    public static void dismissBanner() {
        HwAdHelper.INSTANCE.dismissBanner();
    }
}

5.然后就是HwAgconnectHelper 的脚本


//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.cocos.adsdk.java;

import android.app.Activity;
import android.os.Bundle;
import com.huawei.agconnect.remoteconfig.AGConnectConfig;
import com.huawei.agconnect.remoteconfig.ConfigValues;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hms.analytics.HiAnalytics;
import org.jetbrains.annotations.NotNull;

public class HwAgconnectHelper {
    public static final String TAG = "HwAgconnectHelper";

    public HwAgconnectHelper() {
    }

    public static void initHiAnalytics(Activity activity) {
        HiAnalytics.getInstance(activity);
        System.out.println("HwAgconnectHelperHiAnalytics 初始化成功");
    }

    public static void logEvent(Activity activity, String event) {
        System.out.println("HwAgconnectHelperlogEvent 调用成功");
        Bundle bundle = new Bundle();
        bundle.putString(event, event);
        HiAnalytics.getInstance(activity).onEvent(event, bundle);
    }

    public static String getRemoteStringValue(String key) {
        System.out.println("HwAgconnectHelpergetRemoteStringValue 调用成功");
        AGConnectConfig config = initConfig(key);
        String result = config.getValueAsString(key);
        System.out.println("HwAgconnectHelpergetValueAsString 值为 = " + result);
        return result;
    }

    public static Double getRemoteDoubleValue(String key) {
        System.out.println("HwAgconnectHelpergetRemoteDoubleValue 调用成功");
        AGConnectConfig config = initConfig(key);
        return config.getValueAsDouble(key);
    }

    public static Long getRemoteLongValue(String key) {
        System.out.println("HwAgconnectHelpergetRemoteLongValue 调用成功");
        AGConnectConfig config = initConfig(key);
        return config.getValueAsLong(key);
    }

    @NotNull
    private static AGConnectConfig initConfig(final String key) {
        final AGConnectConfig config = AGConnectConfig.getInstance();
        ConfigValues last = config.loadLastFetched();
        config.apply(last);
        config.fetch(0L).addOnSuccessListener(new OnSuccessListener() {
            public void onSuccess(ConfigValues configValues) {
                System.out.println("HwAgconnectHelperinitConfig onSuccess  值为-> " + config.getValueAsString(key));
            }
        }).addOnFailureListener(new OnFailureListener() {
            public void onFailure(Exception e) {
                System.out.println("HwAgconnectHelperinitConfig onFailure ");
            }
        });
        return config;
    }
}


如果不懂得怎么样用Android导出AAR给unity调用的,可以到这里看一下学习https://www.jianshu.com/p/e174222809ea

你可能感兴趣的:(unity接入华为huawei 广告,分析,远程配置等功能)