unity 接入fyber广告SDK

2 篇文章 0 订阅

最近集成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 initialization
	void 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;
    }

}

每一种广告都一样,先请求广告,请求成功后才可以展示。

这里注意广告请求失败是正常的,因为有时候广告量少很久才会被分配到,如果请求失败只要重新获取即可。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值