最近公司的项目新接入了Admob广告SDK,本文介绍下Admob插屏、鼓励视频、Banner等三种广告的接入方法。

官方接入文档

增加Admob SDK

(1)在app module下的build.gradle中增加代码,如下:

dependencies {
    implementation 'com.google.android.gms:play-services-ads:21.4.0'
}

(2)在AndroidManifest中增加代码,如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application>
        <meta-data
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-xxxxxxxxxxxxxxxx~yyyyyyyyyy"/>
    </application>
</manifest>

初始化SDK

经过MobileAdsinitialize方法进行初始化,代码如下:

class AdmobExampleActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MobileAds.initialize(this, object : OnInitializationCompleteListener {
            override fun onInitializationComplete(initializationStatus: InitializationStatus) {
                val readyAdapter = initializationStatus.adapterStatusMap.entries.find {
                    // 判别适配器初始化的状况
                    // 准备就绪 AdapterStatus.State.READY
                    // 没准备好 AdapterStatus.State.NOT_READY
                    it.value.initializationState == AdapterStatus.State.READY
                }
                // 有恣意一种适配器初始化成功就能够开始加载广告
                if (readyAdapter != null) {
                    // 适配器的名称
                    val adapterName = readyAdapter.key
                }
            }
        })
    }
}

插屏广告

插屏广告的加载、展现等代码如下:

class AdmobExampleActivity : AppCompatActivity() {
    private lateinit var binding: LayoutAdmobExampleActivityBinding
    private var interstitialAd: InterstitialAd? = null
    // 插屏广告加载状况的回调
    private val interstitialAdLoadCallback = object : InterstitialAdLoadCallback() {
        override fun onAdLoaded(interstitialAd: InterstitialAd) {
            super.onAdLoaded(interstitialAd)
            // 加载成功
            this@AdmobExampleActivity.interstitialAd = interstitialAd
            // 设置广告事情回调
            this@AdmobExampleActivity.interstitialAd?.fullScreenContentCallback = interstitialAdCallback
            // 显示插屏广告
            this@AdmobExampleActivity.interstitialAd?.show(this@AdmobExampleActivity)
        }
        override fun onAdFailedToLoad(loadAdError: LoadAdError) {
            super.onAdFailedToLoad(loadAdError)
            // 加载失利
        }
    }
    // 插屏广告相关事情回调
    private val interstitialAdCallback = object : FullScreenContentCallback() {
        override fun onAdImpression() {
            super.onAdImpression()
            // 被记载为展现成功时调用
        }
        override fun onAdShowedFullScreenContent() {
            super.onAdShowedFullScreenContent()
            // 显示时调用
        }
        override fun onAdClicked() {
            super.onAdClicked()
            // 被点击时调用
        }
        override fun onAdDismissedFullScreenContent() {
            super.onAdDismissedFullScreenContent()
            // 隐藏时调用,此刻毁掉当时的插屏广告目标,从头加载插屏广告
            interstitialAd = null
            loadInterstitialAd()
        }
        override fun onAdFailedToShowFullScreenContent(adError: AdError) {
            super.onAdFailedToShowFullScreenContent(adError)
            // 展现失利时调用,此刻毁掉当时的插屏广告目标,从头加载插屏广告
            interstitialAd = null
            loadInterstitialAd()
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MobileAds.initialize(this, object : OnInitializationCompleteListener {
            override fun onInitializationComplete(initializationStatus: InitializationStatus) {
                ...
                loadInterstitialAd()
            }
        })
    }
    private fun loadInterstitialAd() {
        // adUnitId为Admob后台创立的插屏广告的id
        InterstitialAd.load(this, "adUnitId", AdRequest.Builder().build(), interstitialAdLoadCallback)
    }
}

鼓励视频广告

鼓励视频广告的加载、展现等代码如下:

class AdmobExampleActivity : AppCompatActivity() {
    private lateinit var binding: LayoutAdmobExampleActivityBinding
    private var rewardedAd: RewardedAd? = null
    private val rewardedAdLoadCallback = object : RewardedAdLoadCallback() {
        override fun onAdLoaded(rewardedAd: RewardedAd) {
            super.onAdLoaded(rewardedAd)
            // 加载成功
            this@AdmobExampleActivity.rewardedAd = rewardedAd
            // 设置广告事情回调
            this@AdmobExampleActivity.rewardedAd?.fullScreenContentCallback = rewardedVideoAdCallback
            // 展现广告
            this@AdmobExampleActivity.rewardedAd?.show(this@AdmobExampleActivity, rewardedVideoAdEarnedCallback)
        }
        override fun onAdFailedToLoad(loadAdError: LoadAdError) {
            super.onAdFailedToLoad(loadAdError)
            // 加载失利
        }
    }
    private val rewardedVideoAdCallback = object : FullScreenContentCallback() {
        override fun onAdImpression() {
            super.onAdImpression()
            // 被记载为展现成功时调用
        }
        override fun onAdShowedFullScreenContent() {
            super.onAdShowedFullScreenContent()
            // 显示时调用
        }
        override fun onAdClicked() {
            super.onAdClicked()
            // 被点击时调用
        }
        override fun onAdDismissedFullScreenContent() {
            super.onAdDismissedFullScreenContent()
            // 隐藏时调用,此刻毁掉当时的鼓励视频广告目标,从头加载鼓励视频广告
            rewardedAd = null
            loadRewardedVideoAd()
        }
        override fun onAdFailedToShowFullScreenContent(adError: AdError) {
            super.onAdFailedToShowFullScreenContent(adError)
            // 展现失利时调用,此刻毁掉当时的鼓励视频广告目标,从头加载鼓励视频广告
            rewardedAd = null
            loadRewardedVideoAd()
        }
    }
    private val rewardedVideoAdEarnedCallback = OnUserEarnedRewardListener {
        // 用户获得奖赏回调
        // 奖赏的类型
        val type = it.type
        // 奖赏的金额
        val amount = it.amount
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MobileAds.initialize(this, object : OnInitializationCompleteListener {
            override fun onInitializationComplete(initializationStatus: InitializationStatus) {
                ...
                loadRewardedVideoAd()
            }
        })
        binding.btnShowInterstitialAd.setOnClickListener { showInterstitialAd() }
    }
    private fun loadRewardedVideoAd() {
        // adUnitId为Admob后台创立的鼓励视频广告的id
        RewardedAd.load(this, "adUnitId", AdRequest.Builder().build(), rewardedAdLoadCallback)
    }
}

Banner广告

Banner广告的加载、展现等代码如下:

class AdmobExampleActivity : AppCompatActivity() {
    private lateinit var binding: LayoutAdmobExampleActivityBinding
    private var bannerAdView: AdView? = null
    private val bannerListener = object : AdListener() {
        override fun onAdLoaded() {
            super.onAdLoaded()
            // 广告加载成功
        }
        override fun onAdFailedToLoad(loadAdError: LoadAdError) {
            super.onAdFailedToLoad(loadAdError)
            // 广告加载失利
        }
        override fun onAdImpression() {
            super.onAdImpression()
            // 被记载为展现成功时调用
        }
        override fun onAdClicked() {
            super.onAdClicked()
            // 被点击时调用
        }
        override fun onAdOpened() {
            super.onAdOpened()
            // 广告落地页打开时调用
        }
        override fun onAdClosed() {
            super.onAdClosed()
            // 广告落地页关闭时调用
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        MobileAds.initialize(this, object : OnInitializationCompleteListener {
            override fun onInitializationComplete(initializationStatus: InitializationStatus) {
                createBannerAdView()
            }
        })
    }
    private fun createBannerAdView() {
        // 获取页面的根布局
        val rootView = findViewById<FrameLayout>(android.R.id.content)
        bannerAdView = AdView(this)
        bannerAdView?.run {
            // 设置Banner的尺寸
            setAdSize(AdSize.BANNER)
            // adUnitId为Admob后台创立的Banner广告的id
            adUnitId = "adUnitId"
            // 设置广告事情回调
            adListener = bannerListener
            val bannerViewLayoutParams = FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT)
            // 设置显示在页面的底部中心
            bannerViewLayoutParams.gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
            layoutParams = bannerViewLayoutParams
            alpha = 0f
            // 把 Banner Ad 增加到根布局
            rootView.addView(this)
            //加载广告
            loadAd(AdRequest.Builder().build())
        }
    }
}

测验广告

留意,Admob官方声明晰在开发过程中启用测验广告非常重要,这样您就能够在不向 Google 广告客户收费的情况下点击广告。假如您在非测验形式下点击过多广告,可能会导致您的帐号因无效活动而被告发。

想要测验广告的效果,能够经过两种方法。

  • 运用谷歌供给的测验id

谷歌供给了一整套测验id,运用这套id能够获取Admob的测验广告。

// 测验运用id
ApplicationId:"ca-app-pub-3940256099942544~3347511713"
// 测验插屏广告id
InterstitialUnitId:"ca-app-pub-3940256099942544/1033173712"
// 测验鼓励视频广告id
RewardedVideoUnitId:"ca-app-pub-3940256099942544/5224354917"
// 测验Banner广告id
BannerUnitId:"ca-app-pub-3940256099942544/6300978111"
  • 运用自己运用的id,并注册测验设备

假如想要运用自己运用的id进行测验,能够经过注册测验设备来拉取测验广告。

集成好SDK后,安装App,检查tag为Ads的日志,能够看到测验设备id,如下:

Android Admob接入

获取测验设备id后,经过代码注册测验设备,如下:

MobileAds.setRequestConfiguration(RequestConfiguration.Builder()
    .setTestDeviceIds(arrayListOf("deviceId"))
    .build())

注册好测验设备后从头安装App即可。

示例

整合之后,运用Admob供给的测验设备做了个示例demo。

ExampleDemo github

ExampleDemo gitee

效果如图: