亲宝软件园·资讯

展开

Android Admob接入原理及完整教程示例

ChenYhong 人气:0

添加Admob SDK

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

官方接入文档

(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可以获取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进行测试,可以通过注册测试设备来拉取测试广告。

集成好SDK后,安装App,查看tag为Ads的日志,可以看到测试设备id,如下:

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

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

注册好测试设备后重新安装App即可。

示例

整合之后,使用Admob提供的测试设备做了个示例demo。

ExampleDemo github

ExampleDemo gitee

效果如图:

加载全部内容

相关教程
猜你喜欢
用户评论