简体   繁体   English

如何让 Android Admob App Open Ads 在 21.4.0 中展示?

[英]How do I get Android Admob App Open Ads to show in 21.4.0?

I just upgraded from Admob 20.6.0 to 21.4.0 in an Android project.我刚刚在 Android 项目中从 Admob 20.6.0 升级到 21.4.0。 Up until the upgrade, Admob App Open ads were working as expected.在升级之前,Admob App Open 广告按预期工作。 In 21.4.0 I am getting an error in showAdIfAvailable()在 21.4.0 中,我在showAdIfAvailable()中收到错误

Type mismatch.类型不匹配。 Required: Activity Found: Activity?要求:活动发现:活动?

On this line:在这条线上:

appOpenAd?.show(currentActivity)

Code correct suggests the following, but the problem is this code never runs.代码正确建议如下,但问题是这段代码永远不会运行。

currentActivity?.let { appOpenAd?.show(it) }

Here's the full code for AppOpenManager:下面是 AppOpenManager 的完整代码:

class AppOpenManager(private val myApplication: MainActivity) : DefaultLifecycleObserver, Application.ActivityLifecycleCallbacks {
    private var appOpenAd: AppOpenAd? = null
    private var loadCallback: AppOpenAdLoadCallback? = null
    private var currentActivity : Activity? = null
    private var isShowingAd : Boolean = false
    private var loadTime:Long = 0

    /** Creates and returns ad request.  */
    private fun getAdRequest():AdRequest {
        return AdRequest.Builder().build()
    }
    /** Utility method that checks if ad exists and can be shown. */
    private fun isAdAvailable():Boolean {
        return appOpenAd != null && wasLoadTimeLessThan4HoursAgo()
    }



    /** Constructor  */
    init {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            this.myApplication.registerActivityLifecycleCallbacks(this)
        }
        ProcessLifecycleOwner.get().lifecycle.addObserver(this)
    }


    /** Request an ad  */
    fun fetchAd() {

        if (isAdAvailable()) {
            // Have unused ad, no need to fetch another.
            return
        }
        loadCallback = object : AppOpenAdLoadCallback() {

            override fun onAdLoaded(ad: AppOpenAd) {
                this@AppOpenManager.appOpenAd = ad
                this@AppOpenManager.loadTime = (Date()).time
            }

            override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                println("onAppOpenAdFailedToLoad $loadAdError")
            }

        }
        val request: AdRequest = getAdRequest()

        AppOpenAd.load(myApplication, StaticData.appOpenID, request, AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback as AppOpenAdLoadCallback)

    }


    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        showAdIfAvailable()
        println("onStart")
    }


    private fun showAdIfAvailable() {
        // Only show ad if there is not already an app open ad currently showing and an ad is available.
        if (!isShowingAd && isAdAvailable()){
            println("Will show ad.")
            val fullScreenContentCallback = object: FullScreenContentCallback() {
                override fun onAdDismissedFullScreenContent() {
                    // Set the reference to null so isAdAvailable() returns false.
                    this@AppOpenManager.appOpenAd = null
                    isShowingAd = false
                    fetchAd()
                }
                override fun onAdFailedToShowFullScreenContent(adError: AdError) {}
                override fun onAdShowedFullScreenContent() {
                    isShowingAd = true
                }
            }
            appOpenAd?.fullScreenContentCallback = fullScreenContentCallback
            appOpenAd?.show(currentActivity) // Type mismatch. Required: Activity Found: Activity?
        }
        else
        {
            println("Can not show ad... FETCH ONE INSTEAD!")
            fetchAd()
        }
    }


    /** Utility method to check if ad was loaded more than n hours ago. */
    private fun wasLoadTimeLessThan4HoursAgo():Boolean {
        val dateDifference = (Date()).time - this.loadTime
        val numMilliSecondsPerHour:Long = 3600000
        return (dateDifference < (numMilliSecondsPerHour * 4))
    }

    override fun onActivityPaused(activity: Activity) {
        println("⚠️ onActivityPaused")
    }

    override fun onActivityStarted(activity: Activity) {
        println("⚠️ onActivityStarted")
        currentActivity = activity
    }

    override fun onActivityDestroyed(activity: Activity) {
        println("⚠️ onActivityDestroyed")
        currentActivity = null
    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
        println("⚠️ onActivitySaveInstanceState")
    }

    override fun onActivityStopped(activity: Activity) {
        println("⚠️ onActivityStopped")
    }

    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
        println("⚠️ onActivityCreated")
    }

    override fun onActivityResumed(activity: Activity) {
        println("⚠️ onActivityResumed")
        currentActivity = activity
    }

}

And in MainActivity:在 MainActivity 中:

private var appOpenManager: AppOpenManager? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //...
    appOpenManager = AppOpenManager(this)
}

How do I get Android Admob App Open Ads to show in 21.4.0如何让 Android Admob App Open Ads 在 21.4.0 中显示

Type mismatch.类型不匹配。 Required: Activity Found: Activity?要求:活动发现:活动?

this error came because they made a major change出现此错误是因为他们进行了重大更改

Added @NonNull annotations in every method that previously did not explicitly define nullability.在以前未明确定义可空性的每个方法中添加 @NonNull 注释。 -- in 21.0.0 -- 在21.0.0


but the problem is this code never runs currentActivity?.let { appOpenAd?.show(it) }但问题是这段代码永远不会运行currentActivity?.let { appOpenAd?.show(it) }

That is a correct way to solve the above error.这是解决上述错误的正确方法。 I'll assume here that currentActivity is null or addOpenAd is null so the show(it) function call doesn't happen.我在这里假设addOpenAd currentActivity null 所以show(it) function 调用不会发生。 Without logcat it's hard to see the root cause is, but here are a few things to check.如果没有 logcat,很难看出根本原因,但这里有一些要检查的事项。 I think one of these will be the solution:我认为其中之一将是解决方案:

  1. Ensure that onAdFailedToLoad doesn't get called by looking for the log line.通过查找日志行确保不会调用onAdFailedToLoad This will make sure that appOpenAd is assigned.这将确保分配了appOpenAd
  2. Make sure you're testing on Q+, because only on those versions will your code work.确保您在 Q+ 上进行测试,因为只有在这些版本上您的代码才能工作。 On older versions currentActivity will never get assigned.在旧版本上, currentActivity永远不会被分配。 Because the lifecycle callbacks from registerActivityLifecycleCallbacks will not be registered.因为registerActivityLifecycleCallbacks的生命周期回调不会被注册。
  3. It could be a timing issue too, you might need an additional code path to prepare for this case:这也可能是一个时间问题,您可能需要额外的代码路径来为这种情况做准备:
    • App starts and ad starts loading in the background应用启动,广告开始在后台加载
      ( appOpenAd = null, currentActivity = null ) appOpenAd = null, currentActivity = null
    • Activity is started and shown活动已启动并显示
      ( appOpenAd = null, currentActivity = !null ) ( appOpenAd = null, currentActivity = !null )
      showAdIfAvailable is called, but there's no ad yet showAdIfAvailable ,但还没有广告
      BUG: it'll start loading another one! BUG:它会开始加载另一个!
    • Ad finishes loading广告加载完毕
      (appOpenAd =,null, currentActivity = !null) (appOpenAd =,null, currentActivity = !null)
      BUG: nothing else is called from onAdLoaded BUG:没有从onAdLoaded调用任何其他东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM