Doris232 发表于 2021-7-8 16:37

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

因为华为没有直接给unity调的SDK,要用到android写一个aar的插件给unity来调用
1.AndroidMainfest.xml 这里要配置的内容
    <meta-data android:name="install_channel" android:value="AppGallery"/>    <meta-data android:name="com.huawei.hms.client.channel.androidMarket" android:value="false" />    <meta-data android:name="HW_AD_APPLICATION_ID" android:value="app_id" />    <meta-data android:name="HW_BANNER_ID" android:value="banner_id" />    <meta-data android:name="HW_INTERSTITIAL_ID" android:value="interstitial_id" />
2.然后新建一个HuaWeiManager.cs这个脚本要接受到android的回调的话必须要放在场景上面挂着
using System.Collections;using System.Collections.Generic;using QFramework;using UnityEngine;#if UNITY_ANDROID&&huaweipublic class HuaWeiManager : MonoSingleton<HuaWeiManager> {    AndroidJavaClass jc;    AndroidJavaObject jo;    void Start()    {      jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");      jo = jc.GetStatic<AndroidJavaObject>("currentActivity");    }    /// <summary>    /// 发送事件    /// </summary>    /// <param name="strEvent"></param>    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<AndroidJavaObject>("currentActivity");            javaClass.CallStatic("logEvent", jo,strEvent);      } else {            Debug.Log("=====HW_LogEvent==null====");      }    }    /// <summary>    /// 远程配置    /// </summary>    /// <param name="strKey"></param>    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<AndroidJavaObject>("currentActivity");            string str= javaClass.CallStatic<string>("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<AndroidJavaObject>("currentActivity");            javaClass.CallStatic("init", jo,true);      } else {            Debug.Log("=====InitHuiwei==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<AndroidJavaObject>("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<AndroidJavaObject>("currentActivity");            javaClass.CallStatic("dismissBanner");      } else {            Debug.Log("=====HideBanner==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<AndroidJavaObject>("currentActivity");            javaClass.CallStatic("showInterstitialAd");      } else {            Debug.Log("=====ShowInterstitial==null====");      }    }    /// <summary>    /// 广告获取成功时调用banner    /// </summary>    public void onAdLoaded_banner_callback() {      Debug.Log("===HuaWeiManager.onAdLoaded_banner_callback===");    }    /// <summary>    /// 广告获取失败时调用banner    /// </summary>    /// <param name="errorCode"></param>    public void onAdFailed_banner_callback(string errorCode) {      Debug.Log("===HuaWeiManager.onAdFailed_banner_callback===");    }    /// <summary>    /// 广告打开时调用banner    /// </summary>    public void onAdOpened_banner_callback() {      Debug.Log("===HuaWeiManager.onAdOpened_banner_callback===");    }    /// <summary>    /// 广告点击时调用banner    /// </summary>    public void onAdClicked_banner_callback() {      Debug.Log("===HuaWeiManager.onAdClicked_banner_callback===");    }    /// <summary>    /// 广告关闭时调用banner    /// </summary>    public void onAdClosed_banner_callback() {      Debug.Log("===HuaWeiManager.onAdClosed_banner_callback===");    }    /// <summary>    /// 广告获取成功时调用interstitial    /// </summary>    public void onAdLoaded_interstitial_callback() {      Debug.Log("===HuaWeiManager.onAdLoaded_interstitial_callback===");    }    /// <summary>    /// 广告获取失败时调用interstitial    /// </summary>    /// <param name="errorCode"></param>    public void onAdFailed_interstitial_callback(string errorCode) {      Debug.Log("===HuaWeiManager.onAdFailed_interstitial_callback===");    }    /// <summary>    /// 广告打开时调用interstitial    /// </summary>    public void onAdOpened_interstitial_callback() {      Debug.Log("===HuaWeiManager.onAdOpened_interstitial_callback===");    }    /// <summary>    /// 广告点击时调用interstitial    /// </summary>    public void onAdClicked_interstitial_callback() {      Debug.Log("===HuaWeiManager.onAdClicked_interstitial_callback===");    }    /// <summary>    /// 广告关闭时调用interstitial    /// </summary>    public void onAdClosed_interstitial_callback() {      Debug.Log("===HuaWeiManager.onAdClosed_interstitial_callback===");    }    /// <summary>    /// 广告离开时调用interstitial    /// </summary>    public void onAdLeave_interstitial_callback() {      Debug.Log("===HuaWeiManager.onAdLeave_interstitial_callback===");    }    /// <summary>    ///广告曝光时调用interstitial    /// </summary>    public void onAdImpression_interstitial_callback() {      Debug.Log("===HuaWeiManager.onAdImpression_interstitial_callback===");    }}#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**BUILD_SCRIPT_DEPS**}}allprojects {    repositories {      mavenCentral()      google()      jcenter()      maven {url 'https://developer.huawei.com/repo/'} //huawei      flatDir {            dirs 'libs'      }    }}// Android Resolver Repos Endapply plugin: 'com.android.application'//huiweiapply plugin: 'com.huawei.agconnect'apply plugin: 'kotlin-android'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')    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'}//这里主要是为了把华为的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 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<ConfigValues>() {            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;    }}
页: [1]
查看完整版本: unity接入华为huawei 广告,分析,远程配置等功能