跳至主要內容

SDK 接入准备及初始化说明

大约 10 分钟

SDK 接入准备及初始化说明

一、说明

本文档旨在帮助 Android 应用开发者在程序中快速集成 Mobit SDK。开发者仅需执行基础配置,即可轻松展示个性化广告内容。为了掌握SDK的具体使用方法,请仔细阅读以下文档。

二、接入前准备

  1. 接入Mobit SDK前,请联系Mobit 运营,在Mobit平台添加应用、广告位、广告网络等信息,获取请求广告所需的应用 ID 和广告位 ID。
  2. 下载 SDK 并集成到应用内。集成完毕后,首先需要先初始化SDK,并填写平台创建的AppID(应用ID)。然后根据您的需求接入不同的广告功能,按照规范调用各个广告类型方法。
  3. 每一次广告加载时都需要填写sposId(广告位ID)。

三、接入 SDK

(一)导入aar

SDK接入使用aar的方式进行接入,解压平台提供的Mobit 聚合广告SAAdSDK文件,在压缩包中找到adalliance_x.x.x.aar和第三方平台 aar,拷贝aar库到libs文件中 。

SDK 下载地址:开发者可以从下载中心open in new window获取

(二)添加依赖

在根目录的build.gradle中添加:

buildscript {
    repositories {
        google()
        jcenter()
        //mintegral sdk依赖   引入mintegral sdk需要添加此maven
        maven {
            url  "https://dl-maven-android.mintegral.com/repository/mbridge_android_sdk_oversea"
        }
        //以下两个maven用于在您未自定义OAID时获取OAID,如果您已经依赖移动安全联盟(MSA)的aar
        //请检查该aar包中是否已经存在huawei或hihonor的路径,如存在,则不需要再次引用
        maven { url 'https://developer.huawei.com/repo' }
        maven { url 'https://developer.hihonor.com/repo' }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.0"
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    	//mintegral sdk依赖   引入mintegral sdk需要添加此maven
        maven {
            url  "https://dl-maven-android.mintegral.com/repository/mbridge_android_sdk_oversea"
        }
        //以下两个maven用于在您未自定义OAID时获取OAID,如果您已经依赖移动安全联盟(MSA)的aar
        //请检查该aar包中是否已经存在huawei或hihonor的路径,如存在,则不需要再次引用
        maven { url 'https://developer.huawei.com/repo' }
        maven { url 'https://developer.hihonor.com/repo' }
    }
}

在app工程下的build.gradle文件中添加依赖,代码如下:

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.12.0'
    implementation 'com.google.code.gson:gson:2.8.0'
    //Glide
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'

    //广告alliance sdk
    implementation(name: 'adalliance_2.11.1_release', ext: 'aar')
    implementation 'commons-codec:commons-codec:1.15'
	  //优推广告sdk
	  implementation(name: 'adalliance_adn_sdk.3.8.5', ext: 'aar')
    //快手联盟广告sdk
    implementation(name: 'kssdk-ad-3.3.69', ext: 'aar')
    //穿山甲
    implementation(name: 'open_ad_sdk_6.4.1.5', ext: 'aar')
    //优量汇
    implementation(name: 'GDTSDK.unionNormal.4.603.1473 ', ext: 'aar')
    //Sigmob
    implementation(name: 'wind-sdk-4.19.5', ext: 'aar')
    implementation(name: 'wind-common-1.7.2', ext: 'aar')
    //百度广告
    implementation(name:'Baidu_MobAds_SDK-release_v9.371',ext:'aar')
    //倍孜广告
    implementation(name: 'beizi_fusion_sdk_4.90.2.55', ext: 'aar')
    implementation(name: 'beizi_ad_sdk_3.4.20.35', ext: 'aar')
    //Oneway
    implementation(name: 'Oneway-2.5.9-release', ext: 'aar')
    //mtg
    implementation 'com.mbridge.msdk.oversea:reward:16.8.41'
    implementation 'com.mbridge.msdk.oversea:mbbid:16.8.41'
    implementation 'com.mbridge.msdk.oversea:mbnative:16.8.41'
    implementation 'com.mbridge.msdk.oversea:mbnativeadvanced:16.8.41'
    implementation 'com.mbridge.msdk.oversea:newinterstitial:16.8.41'
    implementation 'com.mbridge.msdk.oversea:mbbanner:16.8.41'
    implementation 'com.mbridge.msdk.oversea:mbsplash:16.8.41'

    implementation 'com.tencent:mmkv:1.0.19'
    implementation 'com.google.android.exoplayer:exoplayer-core:2.13.3'
    implementation 'com.google.android.exoplayer:exoplayer-ui:2.13.3'

    //以下两个依赖用于在您未自定义OAID时获取OAID,如果您已经依赖移动安全联盟(MSA)的aar
    //请检查该aar包中是否已经存在huawei或hihonor的路径,如存在,则不需要再次引用
    implementation 'com.huawei.hms:ads-identifier:3.4.62.300'
    implementation 'com.hihonor.mcs:ads-identifier:1.0.2.301'
}

(三)AndroidManifest.xml ⽂件配置

需要相关权限,请在您的App的AndroidManifest.xml⽂件中,添加配置如下:

<!--网络状态-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--联网权限-->
<uses-permission android:name="android.permission.INTERNET" />
<!--获取设备标识-->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--获取MAC地址-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!--获取安装应用权限-->
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<!--读写权限-->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<!--可选权限-->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!--建议添加权限,若添加此权限,需要在您的用户隐私文档中声明! -->
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />

<!-- 穿山甲如果有视频相关的广告且使用textureView播放,请务必添加,否则黑屏 -->
<uses-permission android:name="android.permission.WAKE_LOCK/>
<!--必要权限,解决安全风险漏洞,发送和注册广播事件需要调用带有传递权限的接口-->
<permission
    android:name="${applicationId}.openadsdk.permission.TT_PANGOLIN"
    android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.openadsdk.permission.TT_PANGOLIN" />

<provider
   android:name="com.alliance.ssp.ad.utils.NMSSPFileProvider"
   android:authorities="${applicationId}.NMSSPFileProvider"
   android:exported="false"
   android:grantUriPermissions="true">
   <meta-data
      android:name="android.support.FILE_PROVIDER_PATHS"
      android:resource="@xml/nmssp_file_path" />
</provider>

<!-- 穿山甲 start -->
<provider
     android:name="com.bytedance.sdk.openadsdk.TTFileProvider"
     android:authorities="${applicationId}.TTFileProvider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/file_paths" />
</provider>

 <provider
     android:name="com.bytedance.sdk.openadsdk.multipro.TTMultiProvider"
     android:authorities="${applicationId}.TTMultiProvider"
     android:exported="false" />
<!-- 穿山甲 end -->

<!-- 优量汇 start -->
<!-- targetSDKVersion >= 24时才需要添加这个provider。provider的authorities属性的值为${applicationId}.fileprovider,
    请开发者根据自己的${applicationId}来设置这个值,例如本例中applicationId为"com.qq.e.union.demo">
<provider
     android:name="com.qq.e.comm.GDTFileProvider"
     android:authorities="${applicationId}.gdt.fileprovider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/gdt_file_path" />
</provider>
<!-- 优量汇 end -->

<!-- sigmob start -->
<activity
    android:name="com.sigmob.sdk.base.common.AdActivity"
    android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
    />
<!-- targetSDKVersion >= 24时才需要添加这个provider。
    provider的authorities属性的值为${applicationId}.sigprovider -->
<provider
    android:name="com.sigmob.sdk.SigmobFileProvider"
    android:authorities="${applicationId}.sigprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/sigmob_provider_paths"/>
</provider>
<!-- sigmob end -->

(四)ABI 架构

部分广告平台的SDK中带有so库

建议:在build.gradle中添加如下配置

defaultConfig {
    ...
    ndk{
        abiFilters 'armeabi-v7a','arm64-v8a'
    }
}

(五)在 res/xml 目录下添加 xml 文件

添加文件pangle_file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path name="tt_external_root" path="." />
    <external-path name="tt_external_download" path="Download" />
    <external-files-path name="tt_external_files_download" path="Download" />
    <files-path name="tt_internal_file_download" path="Download" />
    <cache-path name="tt_internal_cache_download" path="Download" />
</paths>

添加文件 gdt_file_path.xml

<paths>
    <!-- 这个下载路径也不可以修改,必须为com_qq_e_download -->
    <external-cache-path
        name="gdt_sdk_download_path1"
        path="com_qq_e_download" />
    <cache-path
        name="gdt_sdk_download_path2"
        path="com_qq_e_download" />
</paths>

添加文件 sigmob_provider_paths.xml

<paths>
    <!-- 这个下载路径不可以修改,SigDownload -->
    <external-cache-path
        name="SigMob_root"
        path="SigDownload" />
    <external-path
        name="SigMob_root_external"
        path="." />
</paths>

(六)混淆配置

请确保您的应⽤打包混淆时,请在混淆配置⽂件proguard-rules.pro,添加如下配置:

-keepclassmembers class **.R$* {
    public static <fields>;
}
-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.app.backup.BackupAgentHelper
-keep public class * extends android.preference.Preference
-keep public class * extends android.app.Fragment

-ignorewarnings
-keep class androidx.annotation.** {*;}
-keep class com.alliance.ssp.ad.api.** { *; }

# Mobit 聚合 sdk
-keep class com.alliance.** {*;}
-keep class com.gameley.templatesdk.** {*;}

# sigmob sdk
-dontwarn android.support.v4.**
-keep class android.support.v4.** { *; }
-keep interface android.support.v4.** { *; }
-keep public class * extends android.support.v4.**
-keep class sun.misc.Unsafe { *; }
-dontwarn com.sigmob.**
-keep class com.sigmob.**.**{*;}

# 穿山甲sdk
-keep class bykvm*.**
-keep class com.bytedance.msdk.adapter.**{ public *; }
-keep class com.bytedance.msdk.api.** {
 public *;
}
-keep class com.bytedance.msdk.base.TTBaseAd{*;}
-keep class com.bytedance.msdk.adapter.TTAbsAdLoaderAdapter{
    public *;
    protected <fields>;
}
-keepclassmembers class * {
    *** getContext(...);
    *** getActivity(...);
    *** getResources(...);
    *** startActivity(...);
    *** startActivityForResult(...);
    *** registerReceiver(...);
    *** unregisterReceiver(...);
    *** query(...);
    *** getType(...);
    *** insert(...);
    *** delete(...);
    *** update(...);
    *** call(...);
    *** setResult(...);
    *** startService(...);
    *** stopService(...);
    *** bindService(...);
    *** unbindService(...);
    *** requestPermissions(...);
    *** getIdentifier(...);
   }
-keep class com.bytedance.pangle.** {*;}
-keep class com.bytedance.sdk.openadsdk.** { *; }
-keep class com.bytedance.frameworks.** { *; }
-keep class ms.bd.c.Pgl.**{*;}
-keep class com.bytedance.mobsec.metasec.ml.**{*;}
-keep class com.ss.android.**{*;}
-keep class com.bytedance.embedapplog.** {*;}
-keep class com.bytedance.embed_dr.** {*;}
-keep class com.bykv.vk.** {*;}

# 快手 sdk
-keep class org.chromium.** {*;}
-keep class org.chromium.** { *; }
-keep class aegon.chrome.** { *; }
-keep class com.kwai.**{ *; }
-dontwarn com.kwai.**
-dontwarn com.kwad.**
-dontwarn com.ksad.**
-dontwarn aegon.chrome.**

# mtg sdk
-keepattributes Signature
-keepattributes *Annotation*
-keep class com.mbridge.** {*; }
-keep interface com.mbridge.** {*; }
-keep class android.support.v4.** { *; }
-dontwarn com.mbridge.**
-keep class **.R$* { public static final int mbridge*; }

# 百度 sdk
-ignorewarnings
-dontwarn com.baidu.mobads.sdk.api.**
-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}
-keep class com.baidu.mobads.** { *; }
-keep class com.style.widget.** {*;}
-keep class com.component.** {*;}
-keep class com.baidu.ad.magic.flute.** {*;}
-keep class com.baidu.mobstat.forbes.** {*;}

# 倍孜 sdk
-dontwarn com.beizi.fusion.**
-dontwarn com.beizi.ad.**
-keep class com.beizi.fusion.** {*; }
-keep class com.beizi.ad.** {*; }

-keep class com.google.android.exoplayer2.** {*; }
-keep class com.github.ykrank.androidlifecycle.** { *; }

如果您的应⽤启⽤了资源混淆或资源缩减,您需要保留SDK的资源,SDK的资源名都是包含nmadssp关键字的。您可以在资源混淆配置⽂件添加如下配置:

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
 tools:keep="@layout/layout_nmssp_*,@id/nmadssp_*,@style/nmadssp_*,
 @drawable/nmadssp_*,@string/nmadssp_*,@color/nmadssp_*,@attr/
nmadssp_*,@dimen/nmadssp_*" />

四、SDK 初始化

请在您应⽤的 Application 的 onCreate() ⽅法中调⽤以下代码来初始化⼴告sdk。

SAAllianceAdInitParams initParams = new SAAllianceAdInitParams.Builder()
                .setInitCallback(new SAAllianceAdInitCallback() {
            @Override
            public void onSuccess() {
                // 初始化成功
            }

            @Override
            public void onFail(int errorCode, String errorMessage) {
                // 初始化失败
            }
        }).build();
SAAllianceAdSdk.init("app id", context, initParams);// appid 必填

(一)SAAllianceAdInitParams.Builder 方法介绍

方法说明是否必填
setDebug(boolean debug)是否开启debug日志打印可选
setInitCallback(SAAllianceAdInitCallback callback)SDK初始化结果回调可选
setMainChannelId(String mainChannelId)主渠道id, 用于数据统计时区分应用分发渠道可选
setChildChannelId(String childChannelId)子渠道id, 用于数据统计时区分应用分发渠道可选
setKeyEvent(boolean keyEvent)是否开启增长助手可选
setPresetStrategies(List<String> presetStrategies)传入Mobit预置策略信息可选
setCSJPresetStrategy(String presetStrategy)传入穿山甲/gromore预置策略信息可选
setLocation(boolean location)是否允许SDK主动使用地理位置信息,SDK默认获取可选
setInstalledAppList(boolean installedAppList)是否允许sdk获取app安装列表,SDK默认获取可选
setCustomAndroidId(String customAndroidId)自定义Android ID,开发者自行获取Android ID传入,传入非空字符串后,SDK将不再主动获取Android ID可选
setCustomIMei(String customIMei)自定义imei,开发者自行获取imei传入,传入非空字符串后,SDK将不再主动获取imei可选
setCustomOAId(String customOAId)自定义oaid,开发者自行获取oaid传入,传入非空字符串后,SDK将不再主动获取oaid可选

注:开通增长助手功能请联系商务

(二)预置策略配置说明

当遇到应用首次安装并且网络拉取配置失败时,客户端表现为请求策略失败,可使用此功能。可在平台提前下载瀑布流配置导入到工程中,在SDK初始化时配置使用。该功能适用于所有广告类型。

读取本地预置策略文件示例代码:

//Mobit 聚合SDK预置策略配置文件,支持广告位下的预置策略配置
List<String> presetStrategies = new ArrayList<>();
presetStrategies.add(jsonFromFilename(application, "Mobit预置策略文件名"));
presetStrategies.add(jsonFromFilename(application, "Mobit预置策略文件名"));
//gromore本地缓存配置
String csjJson = jsonFromFilename(this, "gromore预置策略文件名");

 public static String jsonFromFilename(Application application, String filename) {
    StringBuilder stringBuilder = new StringBuilder();
    try {
        BufferedReader bf = new BufferedReader(new InputStreamReader(
                application.getAssets().open(filename)));
        String line;
        while ((line = bf.readLine()) != null) {
            stringBuilder.append(line);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return stringBuilder.toString();
}

(三)提前初始化广告网络

在2.8.1版本后支持提前初始化广告网络,新增检测聚合SDK初始化状态方法:

private void preInitAdNetwork() {
    SAAllianceAdInitParams.Builder builder = new SAAllianceAdInitParams.Builder();
    // 按正常初始化Mobit SDK时构建SAAllianceAdInitParams,按需调用SAAllianceAdInitParams.Builder方法

    SAAllianceAdInitParams initParams = builder.build();

    List<SAAdNetworkBaseConfig> configs = new ArrayList<>();
    SABaiduNetworkConfig baiduNetworkConfig = new SABaiduNetworkConfig();
    baiduNetworkConfig.setAppId("baidu app id");
    configs.add(baiduNetworkConfig);

    SAGDTNetworkConfig gdtNetworkConfig = new SAGDTNetworkConfig();
    gdtNetworkConfig.setAppId("gdt app id");
    configs.add(gdtNetworkConfig);

    SACSJNetworkConfig csjNetworkConfig = new SACSJNetworkConfig();
    csjNetworkConfig.setAppId("csj/gromore app id");
    configs.add(csjNetworkConfig);

    SAKSNetworkConfig ksNetworkConfig = new SAKSNetworkConfig();
    ksNetworkConfig.setAppId("kuaishou app id");
    configs.add(ksNetworkConfig);

    SASigmobNetworkConfig sigmobNetworkConfig = new SASigmobNetworkConfig();
    sigmobNetworkConfig.setAppId("sigmob app id");
    sigmobNetworkConfig.setApiKey("sigmob api key");
    configs.add(sigmobNetworkConfig);

    SAMintegralNetworkConfig mintegralNetworkConfig = new SAMintegralNetworkConfig();
    mintegralNetworkConfig.setAppId("mintegral app id");
    mintegralNetworkConfig.setApiKey("mintegral api key");
    configs.add(mintegralNetworkConfig);

    SAOnewayNetworkConfig onewayNetworkConfig = new SAOnewayNetworkConfig();
    onewayNetworkConfig.setAppId("oneway app id");
    configs.add(onewayNetworkConfig);

    SAAdScopeNetworkConfig adScopeNetworkConfig = new SAAdScopeNetworkConfig();
    adScopeNetworkConfig.setAppId("ad scope app id");
    configs.add(adScopeNetworkConfig);

    SAYouTuiNetworkConfig youTuiNetworkConfig = new SAYouTuiNetworkConfig();
    youTuiNetworkConfig.setAppId("youtui app id");
    configs.add(youTuiNetworkConfig);

    SAAllianceAdSdk.preInitNetworkWithConfigs(configs, getApplication(), initParams);
}

当冷启动时初始化逻辑和首次加载广告的逻辑代码不方便写到一起时,sdk提供如下方法:

if (SAAllianceAdSdk.checkSDKInitStatus()) {
    // 已初始化完毕!
    // 可以开始加载广告
} else {
    SAAllianceAdSdk.checkSDKInitStatusWithListener(new SAAllianceAdInitCallback() {
        @Override
        public void onSuccess() {
            // 已初始化完毕!
            // 可以开始加载广告
        }
    
        @Override
        public void onFail(int var1, String var2) {
            // 初始化失败
        }
    });
}

五、填充广告源信息获取

public class SAAdSourceInfo {
    public enum AdnType {
        Unknown,
        KuaiShou,
        YouLiangHui,
        ChuanShanJia,
        Gromore,
        Baidu,
        Sigmob,
        YouTui,
        Mintegral,
        OneWay,
        AdScope,
        Other;
    }
    // 广告网络名称
    public String getAdnName();
    // 代码位ID,即所在广告网络的广告位ID
    public String getCodeId();
    // 广告位ID,即mobit平台广告位ID
    public String getSourceId();
    // 广告网络类型
    public AdnType getAdnType();
}

在广告加载成功后,可调用getFillAdSourceInfo()方法获取SAAdSourceInfo

六、获取瀑布流代码位失败信息

在广告加载成功和失败的回调中,可调用List<AdError> getAdErrorList()方法获取AdError对象数组,对象包含信息如下:

public class AdError {
    // 对应广告网络名称
    public String getPlatformName();
    public String getAdSourceId();
    // 代码位ID
    public String getCodeId();
    // 错误码
    public int getAdErrorCode();
    // 错误信息
    public String getAdErrorMsg();
}
上次编辑于: