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空物体把HuaWeiManager.cs 这个脚本要接受到android的回调的话必须要放在场景上面挂着

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

#if UNITY_ANDROID&&huawei
public 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 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<AndroidJavaObject>("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<AndroidJavaObject>("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<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 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<AndroidJavaObject>("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<AndroidJavaObject>("currentActivity");
            javaClass.CallStatic("showInterstitialAd");
        } else {
            Debug.Log("=====ShowInterstitial==null====");
        }
    }

    /// <summary>
    /// 广告获取成功时调用banner
    /// </summary>
    public void onAdLoaded_banner_callback(string str) {
        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==="+errorCode);

    }

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

    }

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

    }

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

    }

    /// <summary>
    /// 广告获取成功时调用interstitial
    /// </summary>
    public void onAdLoaded_interstitial_callback(string str) {
        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==="+ errorCode);

    }

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

    }

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

    }

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

    }

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

    }

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

    }

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

    }

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

    }

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

    }

    /// <summary>
    /// 激励广告奖励达成,发放奖励reward
    /// </summary>
    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<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;
    }
}


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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 205,132评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,802评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,566评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,858评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,867评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,695评论 1 282
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,064评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,705评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,915评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,677评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,796评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,432评论 4 322
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,041评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,992评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,223评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,185评论 2 352
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,535评论 2 343

推荐阅读更多精彩内容