我正在主要活动中加载一个简单的横幅广告。问题是,每当我启动应用程序时,它在白屏上停留约2秒钟,然后加载UI。
问题不在于应用程序代码,因为在我添加用于立即启动的广告应用程序之前。这是我加载广告的代码:
在onCreate
中:
MobileAds.initialize(this, "ca-app-pub-#######")
val mAdView: AdView = findViewById(R.id.adView)
mAdView.visibility = View.GONE
val adRequest = AdRequest.Builder().build()
val adView = AdView(this)
adView.adSize = AdSize.BANNER
adView.adUnitId = "ca-app-pub-3940256099942544/6300978111" <- test id
initializeAds(mAdView, adRequest)
initializeAds()
:
fun initializeAds(adView: AdView, adRequest: AdRequest){
adView.loadAd(adRequest)
adView.adListener = object : AdListener(){
override fun onAdLoaded() {
super.onAdLoaded()
if (adView.visibility == View.GONE) {
adView.visibility = View.VISIBLE
}
}
override fun onAdFailedToLoad(p0: Int) {
super.onAdFailedToLoad(p0)
adView.visibility = View.GONE
}
}
}
有没有什么方法可以加载没有UI滞后的广告?
答案 0 :(得分:1)
将此作为横幅广告ID ca-app-pub-3940256099942544/6300978111
答案 1 :(得分:0)
好的,终于我找到了一种快速的解决方法。我发现MobileAds.initialize(context, id)
和AdRequest.Builder().build()
出现了滞后。显然,除非完全执行onCreate
,否则活动将不会完全加载。要绕过我使用Handler
来延迟MobileAds.initialize
和AdRequest.Builder().build
的时间,那么它不会造成UI滞后。这是我更新的代码:
// we can't delay UI tasks so we need initialize adView here - it's not heavy task anyway
val mAdView: AdView = findViewById(R.id.adView)
mAdView.visibility = View.GONE
//delay ads to be displayed 2 sec after Activity is loaded
Handler().postDelayed({
MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713")
initializeAds(mAdView)
}, 2000)
initializeAds(AdView)
:
fun initializeAds(adView: AdView) {
adView.loadAd(AdRequest.Builder().build())
adView.adListener = object : AdListener() {
override fun onAdLoaded() {
super.onAdLoaded()
//if ad is loaded just show it
if (adView.visibility == View.GONE) {
adView.visibility = View.VISIBLE
}
}
override fun onAdFailedToLoad(p0: Int) {
//if we can't show ad just hide it
super.onAdFailedToLoad(p0)
adView.visibility = View.GONE
}
}
}
如果有人遇到同样的问题,我希望这会有所帮助
答案 2 :(得分:0)
Domin建议您为MobileAds.Initialize()进行大约2000毫秒的发布延迟。请不要那样做。 2秒后,UI会冻结!用户会非常恼火。最好是启动速度比应用程序仅在用户开始使用时就没有响应的速度慢。
答案 3 :(得分:-1)
//Kotlin Code
//Heavy tasks in Second Thread
//finally loadAd() in UI thread
Thread{
MobileAds.initialize(this);
val mAdView = findViewById<AdView>(R.id.adview);
val adRequest = AdRequest.Builder().build();
runOnUiThread {
mAdView.loadAd(adRequest);
}}.start();