在 Android (Kotlin) 上从 Google AdMob (ex. AdMob) 迁移到 Yandex 聚合

要在 Android 上使用 Yandex Ads 聚合替换 Google AdMob (ex. AdMob) 广告,请对您的代码进行以下更改。

集成SDK

将 Yandex Mobile Ads SDK 的依赖项添加到应用级别的模块的 Gradle 文件中(通常为 app/build.gradle)。

dependencies {
    implementation 'com.google.android.gms:play-services-ads:22.5.0'
}
dependencies {
    implementation 'com.yandex.android:mobileads:6.2.0'
    implementation 'com.yandex.ads.mediation:mobileads-admob:22.5.0.0'
    implementation 'com.google.android.gms:play-services-ads:22.5.0'
}

在加载广告之前,使用 initialize() 方法初始化库:

import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.initialization.InitializationStatus

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MobileAds.initialize(this) {
            fun onInitializationComplete(initializationStatus: InitializationStatus?) {

            }
        }
    }
}
import com.yandex.mobile.ads.common.MobileAds

class MainActivity : AppCompatActivity() {
     override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
         MobileAds.initialize(this) {

         }
     }
 }

广告格式

插屏广告

加载广告

import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback

class MainActivity : AppCompatActivity() {
    private var interstitialAd: InterstitialAd? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MobileAds.initialize(this) {
            fun onInitializationComplete(initializationStatus: InitializationStatus?) {
            }
        }
        val adRequest: AdRequest = Builder().build()

        InterstitialAd.load(this, "ca-app-pub-3940256099942544/1033173712", adRequest,
            object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(interstitialAdLoaded: InterstitialAd) {
                    // interstitialAd 引用的值将为 null,直到
                    // 广告完成加载。
                    interstitialAd = interstitialAdLoaded
                    Log.i("TAG", "onAdLoaded")
                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    // 处理错误
                    Log.i("TAG", loadAdError?.toString())
                    interstitialAd = null
                }
            })
    }
}
import com.yandex.mobile.ads.common.MobileAds
import com.yandex.mobile.ads.interstitial.InterstitialAd
import com.yandex.mobile.ads.common.AdRequest

class MainActivity : AppCompatActivity() {
    private var interstitialAd: InterstitialAd? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MobileAds.initialize(this) {

        }

        val adRequest: AdRequest = Builder().build()

        interstitialAd = InterstitialAd(this)
        interstitialAd?.setAdUnitId("demo-interstitial-yandex")
        interstitialAd?.loadAd(adRequest)
    }
}

设置广告回调

在展示广告之前,设置回调以跟踪与广告相关的事件。

import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.FullScreenContentCallback

interstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
    override fun onAdDismissedFullScreenContent() {
        // 当全屏内容被关闭时调用。
        Log.d("TAG", "The ad was dismissed.")
    }

    override fun onAdFailedToShowFullScreenContent(adError: AdError) {
        // 当全屏内容无法显示时调用。
        Log.d("TAG", "The ad failed to show.")
    }

    override fun onAdShowedFullScreenContent() {
        // 当全屏内容显示时调用。
        // 确保将引用设置为 null,
        // 以免再次显示。
        interstitialAd = null
        Log.d("TAG", "The ad was shown.")
    }
}
import com.yandex.mobile.ads.common.ImpressionData
import com.yandex.mobile.ads.common.AdRequestError

interstitialAd?.setInterstitialAdEventListener(object : InterstitialAdEventListener {
    override fun onAdLoaded() {
        Log.i("TAG", "onAdLoaded")
    }

    override fun onAdFailedToLoad(error: AdRequestError) {
        // 处理错误
        Log.i("TAG", error.description)
    }

    override fun onAdDismissed() {
        // 当插屏广告已关闭时调用。
        Log.d("TAG", "The ad was dismissed.")
    }

    override fun onAdShown() {
        // 当插屏广告展示时调用。
        Log.d("TAG", "The ad was shown.")
    }

    override fun onImpression(impressionData: ImpressionData?) {
        // 当跟踪到一次展示时调用。
        Log.d("TAG", "The ad imprassion was tracked.")
    }

    override fun onAdClicked() {
        // 当用户点击广告时调用。
        Log.d("TAG", "The ad was clicked.")
    }

    override fun onReturnedToApplication() {
        // 当用户点击后返回应用程序时调用。
        Log.d("TAG", "The ad was clicked.")
    }

    override fun onLeftApplication() {
        // 当用户点击广告后即将离开应用时调用。
        Log.d("TAG", "The ad left application after click.")
    }
})

显示广告

插屏广告应在应用运行的自然暂停期间展示。例如,在游戏关卡之间或用户完成任务后。要显示插屏广告,请使用 show() 方法。

if (interstitialAd != null) {
    interstitialAd?.show(MyActivity.this)
} else {
     Log.d("TAG", "The interstitial ad wasn't ready yet.")
}
if (interstitialAd?.isLoaded == true) {
    interstitialAd?.show()
} else {
    Log.d("TAG", "The interstitial ad wasn't ready yet.")
}

将 AdView 对象添加到布局中

要显示横幅,请将“BannerAdView”放置在适当的活动或片段中。为此,请将其添加到相应的布局 XML 文件中:

# main_activity.xml
...
  <com.google.android.gms.ads.AdView
      xmlns:ads="http://schemas.android.com/apk/res-auto"
      android:id="@+id/adView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_alignParentBottom="true"
      ads:adSize="BANNER"
      ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
  </com.google.android.gms.ads.AdView>
...
# main_activity.xml
...
  <com.yandex.mobile.ads.banner.BannerAdView
      xmlns:ads="http://schemas.android.com/apk/res-auto"
      android:id="@+id/adView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerHorizontal="true"
      android:layout_alignParentBottom="true">
  </com.yandex.mobile.ads.banner.BannerAdView>
...

在代码中指定所需的属性:

// ...
bannerAdView = (BannerAdView) findViewById(R.id.adView)
bannerAdView.setAdUnitId("demo-banner-yandex")
bannerAdView.setAdSize(AdSize.stickySize(context, 320))
// ...
  • adSize:所需的 横幅尺寸

  • adUnitId:广告单元唯一 ID。如果您应用中的横幅显示在活动的不同实例中,我们建议在 Partner Interface 中为每个横幅创建单独的广告单元 ID。

您还可以通过编程方式创建 BannerAdView 对象:

import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView

val adView = AdView(this)
adView.setAdSize(AdSize.BANNER)
adView.adUnitId = "ca-app-pub-3940256099942544/6300978111"
// 待办:将 adView 添加到您的视图层次结构中。
import com.yandex.mobile.ads.banner.AdSize
import com.yandex.mobile.ads.banner.BannerAdView

val adView = BannerAdView(this)
adView.setAdSize(AdSize.stickySize(context, 320))
adView.setAdUnitId("demo-banner-yandex")
// 待办:将 adView 添加到您的视图层次结构中。

加载广告

import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.initialization.InitializationStatus

class MainActivity : AppCompatActivity() {
    private var adView: AdView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MobileAds.initialize(this) {
            fun onInitializationComplete(initializationStatus: InitializationStatus?) {

            }
        }

        adView = findViewById<AdView>(R.id.adView)
        val adRequest = AdRequest.Builder().build()
        adView?.loadAd(adRequest)
    }
}
import com.yandex.mobile.ads.banner.BannerAdView
import com.yandex.mobile.ads.common.AdRequest
import com.yandex.mobile.ads.common.MobileAds

class MainActivity : AppCompatActivity() {
    private var adView: BannerAdView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MobileAds.initialize(this) {

        }

        adView = findViewById<BannerAdView>(R.id.adView)
        val adRequest: AdRequest = Builder().build()
        adView?.loadAd(adRequest)
    }
}

订阅广告展示事件

要自定义广告的行为,您可以订阅广告生命周期事件。

import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.LoadAdError

adView?.adListener = object : AdListener() {
    override fun onAdLoaded() {
        // 广告加载完成时执行的代码。
    }

    override fun onAdFailedToLoad(adError: LoadAdError) {
        // 广告请求失败时执行的代码。
    }

    override fun onAdOpened() {
        // 广告打开覆盖整个屏幕的叠加层时
        //执行的代码。
    }

    override fun onAdClicked() {
        // 用户点击广告时执行的代码。
    }

    override fun onAdClosed() {
        // 用户在点击广告后即将返回
        // 应用时执行的代码。
    }
}
import com.yandex.mobile.ads.common.AdRequestError
import com.yandex.mobile.ads.common.ImpressionData

adView?.setBannerAdEventListener(object : BannerAdEventListener {
    override fun onAdLoaded() {
        // 广告加载完成时执行的代码。
    }

    override fun onAdFailedToLoad(error: AdRequestError) {
        // 广告请求失败时执行的代码。
    }

    override fun onAdClicked() {
        // 用户点击广告时执行的代码。
    }

    override fun onImpression(impressionData: ImpressionData?) {
        // 当跟踪到一次展示时调用。
    }

    override fun onLeftApplication() {
        // 当用户点击广告后即将离开应用时调用。
    }

    override fun onReturnedToApplication() {
        // 用户在点击广告后即将返回
        // 应用时执行的代码。
    }
})

激励广告

加载激励广告对象

import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.initialization.InitializationStatus
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback

class MainActivity : AppCompatActivity() {
    private var rewardedAd: RewardedAd? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MobileAds.initialize(this) {
            fun onInitializationComplete(initializationStatus: InitializationStatus?) {
            }
        }

        val adRequest: AdRequest = Builder().build()

        RewardedAd.load(this, "ca-app-pub-3940256099942544/5224354917",
            adRequest, object : RewardedAdLoadCallback() {
                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    // 处理错误。
                    Log.d("TAG", loadAdError?.toString())
                    rewardedAd = null
                }

                override fun onAdLoaded(rewardedAd: RewardedAd) {
                    rewardedAd = rewardedAd
                    Log.d("TAG", "Ad was loaded.")
                }
            })
    }
}
import com.yandex.mobile.ads.common.AdRequest
import com.yandex.mobile.ads.common.MobileAds
import com.yandex.mobile.ads.rewarded.RewardedAd

class MainActivity : AppCompatActivity() {
    private var rewardedAd: RewardedAd? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        MobileAds.initialize(this) {

        }

        val adRequest: AdRequest = Builder().build()
        rewardedAd = RewardedAd(this)
        rewardedAd?.setAdUnitId("demo-rewarded-yandex")
    }
}

设置广告回调

import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.AdError

rewardedAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
    override fun onAdShowedFullScreenContent() {
        // 广告显示时调用。
        Log.d(TAG, "Ad was shown.")
    }

    override fun onAdFailedToShowFullScreenContent(adError: AdError) {
        // 广告无法显示调用。
        Log.d(TAG, "Ad failed to show.")
    }

    override fun onAdDismissedFullScreenContent() {
        // 广告关闭时调用。
        // 将广告引用设置为 null,以免再次显示广告。
        Log.d(TAG, "Ad was dismissed.")
    }
}
import com.yandex.mobile.ads.rewarded.RewardedAdEventListener
import com.yandex.mobile.ads.common.AdRequestError
import com.yandex.mobile.ads.rewarded.Reward

rewardedAd?.setRewardedAdEventListener(object : RewardedAdEventListener {
    override fun onAdLoaded() {
        Log.i("TAG", "onAdLoaded")
    }

    override fun onAdFailedToLoad(error: AdRequestError) {
        // 处理错误
        Log.i("TAG", error.description)
    }

    override fun onRewarded(reward: Reward) {
        // 处理奖励。
        Log.d("TAG", "The user earned the reward.")
        val rewardAmount: Int = reward.amount
        val rewardType: String = reward.type
    }

    override fun onAdDismissed() {
        // 当插屏广告已关闭时调用。
        Log.d("TAG", "The ad was dismissed.")
    }

    override fun onAdShown() {
        // 当插屏广告展示时调用。
        Log.d("TAG", "The ad was shown.")
    }

    override fun onImpression(impressionData: ImpressionData?) {
        // 当跟踪到一次展示时调用。
        Log.d("TAG", "The ad impression was tracked.")
    }

    override fun onAdClicked() {
        // 当用户点击广告时调用。
        Log.d("TAG", "The ad was clicked.")
    }

    override fun onReturnedToApplication() {
        // 当用户点击后返回应用程序时调用。
        Log.d("TAG", "The ad was clicked.")
    }

    override fun onLeftApplication() {
        // 当用户点击广告后即将离开应用时调用。
        Log.d("TAG", "The ad left application after click.")
    }
})

显示广告

要显示激励广告,请使用 RewardedAdEventListener 对象来处理奖励事件。

rewardedAd?.let { ad ->
  ad.show(this, OnUserEarnedRewardListener { rewardItem ->
    // 处理奖励。
    val rewardAmount = rewardItem.amount
    val rewardType = rewardItem.type
    Log.d(TAG, "User earned the reward.")
  })
} ?: run {
  Log.d(TAG, "The rewarded ad wasn't ready yet.")
}
if (rewardedAd?.isLoaded == true) {
    rewardedAd?.show()
} else {
    Log.d("TAG", "The rewarded ad wasn't ready yet.")
}

联系支持部门

下一篇