unity 接入fyber廣告SDK

來源:互聯網
上載者:User

最近整合fyber SDK,這裡記錄一下:

後台配置方面的內容是其它人弄好的,我沒有參與,所以這裡不討論,有需要直接參考官方文檔即可:

https://unity.fyber.com/docs/welcome

1.下載unity 包:

https://unity.fyber.com/docs/download-unity-plugin

點擊最下面的按鈕即可下載

下載後是個unity的package,雙擊匯入項目即可。

2.下載對應的廣告包

https://unity.fyber.com/docs/med-network-details


注意前面的是ios的包,後面是android的包

3.把所有包匯入到unity

4.修改Plugins/Android檔案夾下的AndroidManifest檔案

如果沒有檔案自己建立一個,稍後我會給出我的檔案的完整代碼。

進入這個串連:

https://unity.fyber.com/docs/adding-the-bundles#Android SetupAdMob https://unity.fyber.com/docs/adding-the-bundles#Android SetupAdMob

選擇你要接入的廣告:


選中後下面會給出相應的配置代碼:


把這些代碼加入到我們的AndroidManifest檔案中。

下面是我的AndroidManifest檔案:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.unity3d.player" xmlns:tools="http://schemas.android.com/tools" android:installLocation="preferExternal" android:versionCode="1" android:versionName="1.0"><supports-screens android:smallScreens="true" android:normalScreens="true" android:largeScreens="true" android:xlargeScreens="true" android:anyDensity="true" /><application android:theme="@style/UnityThemeSelector" android:icon="@drawable/app_icon" android:label="@string/app_name" ><activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="@string/app_name"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter><meta-data android:name="unityplayer.UnityActivity" android:value="true" /></activity><activity android:name="com.vungle.publisher.VideoFullScreenAdActivity" android:configChanges="orientation|screenSize" />        <activity android:name="com.tapjoy.TJAdUnitActivity" android:configChanges="orientation|screenSize" />        <activity android:name="com.tapjoy.TJContentActivity" android:configChanges="orientation|screenSize" />        <activity android:name="com.tapjoy.mraid.view.ActionHandler" android:configChanges="orientation|screenSize" />        <activity android:name="com.tapjoy.mraid.view.Browser" android:configChanges="orientation|screenSize" />        <activity android:name="com.unity3d.ads.adunit.AdUnitActivity" android:configChanges="orientation|screenSize" /><activity android:name="com.fyber.unity.ads.OfferWallUnityActivity" android:configChanges="orientation|screenSize" /><activity android:name="com.fyber.unity.ads.RewardedVideoUnityActivity" android:configChanges="screenSize|orientation" android:theme="@android:style/Theme.Translucent" android:hardwareAccelerated="true" /><activity android:name="com.fyber.ads.interstitials.InterstitialActivity" android:configChanges="screenSize|orientation" android:theme="@android:style/Theme.Translucent" /><activity android:name="com.fyber.utils.testsuite.TestSuiteActivity" android:label="Integration Test Suite" /><service android:name="com.fyber.cache.CacheVideoDownloadService" android:exported="false" /></application><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /></manifest>
展示廣告

這裡我已經封裝好了廣告相關的方法:

using System.Collections;using System.Collections.Generic;using UnityEngine;namespace FyberPlugin{    public delegate void ADDelegate(FyberManager.enAdCallBackState state, AdFormat format);    /// <summary>    /// ************    /// CREATE BY LIUFENG ON 180104    /// ************    /// 所有廣告相關方法封裝到此類,方便不同項目使用    /// 每種廣告的效果參考官方文檔    /// 參考:https://unity.fyber.com/docs/integrating-sdk#section-android-manifest    /// ************    /// 步驟    /// 1:遊戲啟動時調用InitFyber,進行SDK的初始化    /// 2:所有廣告展示之前必須先調用相應的Request方法載入廣告    /// 3:載入成功會進入回調方法,更具回調參數判斷是否成功    /// 4:載入成功後,可以調用相應的方法展示廣告    /// ************    /// 注:    /// 此SDK只支援IOS和Android平台,unity編輯器中無法進行測試    /// </summary>    public static class FyberManager    {        public enum enAdCallBackState        {            //--------OfferWall-----------            Ready = 0x00000010,//廣告準備完畢            GetFail = 0x00000011,//廣告擷取失敗            ShowFail = 0x00000012,//展示失敗            Start = 0x00000013,//廣告開始            Finished = 0x00000014,//廣告播放完畢            FinishedAborted = 0x00000015,//廣告播放完畢 被關閉        }        /// <summary>        /// 相關配置參數        /// *****不同項目需填入自己的參數*****        /// </summary>        private const string APP_ID = "123456";        private const string SECURITY_TOKEN = "abcd";        /// <summary>        /// 遊戲啟動時需調用此方法進行SDK的初始化        /// 初始化廣告外掛程式        /// C# - START the Fyber Unity Plugin (RECOMMENDED method)        /// </summary>        /// <param name="mode">        /// </param>        public static void InitFyber()        {            //The securityToken and appId are required, and can be found in the Settings of your app in the Dashboard.            Fyber.With(APP_ID)                 .WithSecurityToken(SECURITY_TOKEN)                 .Start().NotifyUserOnReward(false).NotifyUserOnCompletion(false);                    }        /// <summary>        /// Please Note!        /// First you request, then you display it.        /// </summary>        ///         //***********************OfferWall**************************        static ADRequestCallback offerWallRequestCallback = new ADRequestCallback();        //準備廣告 需提前準備        public static void OfferWallRequest(ADDelegate d){            offerWallRequestCallback.SetDelegate(d);            OfferWallRequester.Create().WithCallback(offerWallRequestCallback).Request();        }        //顯示廣告        public static void OfferWallShow(ADDelegate d){            ShowAD(offerWallRequestCallback,d);        }        //***********************RewardedVideo**************************        static ADRequestCallback rewardedVideoRequestCallback = new ADRequestCallback();        //準備廣告 需提前準備        public static void RewardedVideoRequest(ADDelegate d)        {            rewardedVideoRequestCallback.SetDelegate(d);            RewardedVideoRequester.Create().WithCallback(rewardedVideoRequestCallback).Request();        }        //顯示廣告        public static void RewardedVideoShow(ADDelegate d)        {            ShowAD(rewardedVideoRequestCallback, d);        }        //***********************Interstitials**************************        static ADRequestCallback interstitialsRequestCallback = new ADRequestCallback();        //準備廣告 需提前準備        public static void InterstitialsRequest(ADDelegate d)        {            interstitialsRequestCallback.SetDelegate(d);            InterstitialRequester.Create().WithCallback(interstitialsRequestCallback).Request();        }        //顯示廣告        public static void InterstitialsShow(ADDelegate d)        {            ShowAD(interstitialsRequestCallback, d);        }        //***********************Banners**************************        static ADRequestCallback bannersRequestCallback = new ADRequestCallback();        //準備廣告 需提前準備        public static void BannersRequest(ADDelegate d)        {            bannersRequestCallback.SetDelegate(d);            BannerRequester.Create().WithCallback(bannersRequestCallback).Request();        }        //顯示廣告        public static void BannersShow(ADDelegate d)        {            ShowAD(bannersRequestCallback, d);        }        //Hiding and showing a started banner        public static void BannersActivity(bool isshow){            if(bannersRequestCallback.Ad == null){                Debug.Log("bannersRequestCallback is null!! plase call the BannersRequest.");                return;            }            BannerAd bannerAd = bannersRequestCallback.Ad as BannerAd;             if(isshow){                bannerAd.Show();            }else{                bannerAd.Hide();            }        }        //Destroying the banner        public static void BannersDestroy(){            if(bannersRequestCallback.Ad == null){                Debug.Log("bannersRequestCallback is null!! plase call the BannersRequest.");                return;            }            BannerAd bannerAd = bannersRequestCallback.Ad as BannerAd;             bannerAd.Destroy();            bannersRequestCallback.Ad = null;        }        //*******************展示廣告*******************        static void ShowAD(ADRequestCallback reqcb,ADDelegate d){            if (reqcb == null)            {                Debug.Log("需要播放廣告之前,需要先初始化");                d(FyberManager.enAdCallBackState.ShowFail, AdFormat.UNKNOWN);                return;            }            AdPlayCallback adCallback = new AdPlayCallback();            bool isshow = reqcb.Show(adCallback);            if (isshow)            {                adCallback.SetDelegate(d);            }            else            {                d(FyberManager.enAdCallBackState.ShowFail, AdFormat.UNKNOWN);            }        }    }    //handling the asynchronous response after requesting the Offer Wall    //OfferWall CALLBACK    public class ADRequestCallback : RequestCallback    {        public Ad Ad;        ADDelegate addelegate = null;        public void SetDelegate(ADDelegate d)        {            addelegate = d;        }        public void OnAdAvailable(Ad ad)        {            // store ad            Ad = ad;            if (addelegate != null) addelegate(FyberManager.enAdCallBackState.Ready,ad.AdFormat);        }        public void OnAdNotAvailable(AdFormat adFormat)        {            // discard previous stored ad            Ad = null;            if (addelegate != null) addelegate(FyberManager.enAdCallBackState.GetFail,adFormat);        }        public void OnRequestError(RequestError error)        {            // process error            Debug.Log("OnRequestError: " + error.Description);            if (addelegate != null) addelegate(FyberManager.enAdCallBackState.GetFail,AdFormat.UNKNOWN);        }        public bool Show(AdPlayCallback cb)        {            if (Ad != null)            {                Ad.WithCallback(cb).Start();                Ad = null;                return true;            }            else            {                NGUIDebug.Log("還沒有擷取到廣告資料。");            }            return false;        }    }    public class AdPlayCallback : AdCallback    {        ADDelegate addelegate = null;        public void SetDelegate(ADDelegate d){            addelegate = d;        }        public void OnAdStarted(Ad ad)        {            // this is where you mute the sound and toggle buttons if necessary            Debug.Log("OnAdStarted. Ad " + ad.AdFormat + " has started");            if(addelegate != null) addelegate(FyberManager.enAdCallBackState.Start,ad.AdFormat);        }        public void OnAdFinished(AdResult result)        {            // this is the place where you can resume the sound            // reenable buttons, etc            Debug.Log("OnAdFinished. Ad " + result.AdFormat +                " finished with status: " + result.Status +                      " and message: " + result.Message);            if (addelegate == null) return;            if(result.Message == "CLOSE_FINISHED"){                addelegate(FyberManager.enAdCallBackState.Finished, result.AdFormat);            }else{                addelegate(FyberManager.enAdCallBackState.FinishedAborted, result.AdFormat);            }        }    }   }

這裡要記得把APP_ID和SECURITY_TOKEN設定為自己背景內容。

下面是測試方法:

using System.Collections;using System.Collections.Generic;using UnityEngine;using FyberPlugin;[ExecuteInEditMode]  public class ADTest : MonoBehaviour {    const int height = 70;    const int width = 200;    bool isok = false;// Use this for initializationvoid Start () {        FyberManager.InitFyber();        FyberLogger.EnableLogging(true);        FyberCallback.NativeError += OnNativeExceptionReceivedFromSDK;        Invoke("InitFyber", 15f);}    void InitFyber(){        isok = true;        //SDK初始化        NGUIDebug.Log("fyber init finished!!!");    }    int high;    void OnGUI()    {        if (!isok) return;        high = 10;        if (CreateBtn("Test "))        {            IntegrationAnalyzer.ShowTestSuite();        }        //******************OfferWall*********************        if (CreateBtn("OfferWall Request "))        {            FyberManager.OfferWallRequest(AdCallBack);        }        if (CreateBtn("OfferWall Show "))        {            FyberManager.OfferWallShow(AdCallBack);        }        //******************RewardedVideo*********************        if (CreateBtn("RewardedVideo Request "))        {            FyberManager.RewardedVideoRequest(AdCallBack);        }        if (CreateBtn("RewardedVideo Show "))        {            FyberManager.RewardedVideoShow(AdCallBack);        }        //******************Interstitials*********************        if (CreateBtn("Interstitials Request "))        {            FyberManager.InterstitialsRequest(AdCallBack);        }        if (CreateBtn("Interstitials Show "))        {            FyberManager.InterstitialsShow(AdCallBack);        }        //******************Banners*********************        if (CreateBtn("Banners Request "))        {            FyberManager.BannersRequest(AdCallBack);        }        if (CreateBtn("Banners Show "))        {            FyberManager.BannersShow(AdCallBack);        }        if (CreateBtn("Banners Showing "))        {            FyberManager.BannersActivity(true);        }        if (CreateBtn("Banners Hiding "))        {            FyberManager.BannersActivity(false);        }        if (CreateBtn("Banners Destroying "))        {            FyberManager.BannersDestroy();        }    }    public bool CreateBtn(string btnname)    {        bool b = GUI.Button(new Rect(Screen.width / 2 - width / 2, high, width, height), btnname);        high += height + 5;        return b;    }    public void AdCallBack(FyberManager.enAdCallBackState state, AdFormat format){        NGUIDebug.Log("AdCallBack : " + state + " format : " + format);        Debug.Log("AdCallBack : " + state);    }    public void OnNativeExceptionReceivedFromSDK(string message)    {        NGUIDebug.Log("message : " + message );    }    void OnDisable()    {        FyberCallback.NativeError -= OnNativeExceptionReceivedFromSDK;    }}

每一種廣告都一樣,先請求廣告,請求成功後才可以展示。

這裡注意廣告要求失敗是正常的,因為有時候廣告量少很久才會被分配到,如果請求失敗只要重新擷取即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.