-2
我試圖通過一個異步任務如下加載AdMob插頁式廣告:AdMob聯播的插頁式廣告失敗使用的AsyncTask
private class AdLoaderTask extends AsyncTask<InterstitialAd, Integer, InterstitialAd> {
InterstitialAd mLocalInterstitialAd;
protected InterstitialAd doInBackground(InterstitialAd... ads) {
mLocalInterstitialAd = ads[0];
AdRequest.Builder builder = new AdRequest.Builder();
if (BuildConfig.DEBUG) {
builder.addTestDevice("XXXX");
}
AdRequest adRequest = builder.build();
mLocalInterstitialAd.loadAd(adRequest);
return mLocalInterstitialAd;
}
protected void onPostExecute(Long result) {
if (mLocalInterstitialAd.isLoaded()) {
setLoadedInterstitialAd(mLocalInterstitialAd);
} else {
loadInterstitialAd(mLocalInterstitialAd);
}
}
}
我得到這個異常:
07-21 11:11:32.898 E/AndroidRuntime(14359): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
07-21 11:11:32.898 E/AndroidRuntime(14359): at android.os.Handler.<init>(Handler.java:200)
07-21 11:11:32.898 E/AndroidRuntime(14359): at android.os.Handler.<init>(Handler.java:114)
07-21 11:11:32.898 E/AndroidRuntime(14359): at com.google.android.gms.ads.internal.prefetch.b.<init>(:com.google.android.gms.DynamiteModulesA:37)
07-21 11:11:32.898 E/AndroidRuntime(14359): at com.google.android.gms.ads.internal.prefetch.b.<init>(:com.google.android.gms.DynamiteModulesA:31)
07-21 11:11:32.898 E/AndroidRuntime(14359): at com.google.android.gms.ads.internal.c.<init>(:com.google.android.gms.DynamiteModulesA:106)
這是否意味着廣告可以即使任務本身是從UI線程執行的,也不會通過AsyncTask加載?
如何解決這個問題? MobileAds.initialize, setAdUnitId
做似乎在AsyncTask中工作。我錯過了什麼嗎?廣告在不使用AsyncTask時加載正常。可以通過Service
加載?
顯然我失去了一些東西剛剛下投... – CharleyGC
我沒有向AdMob做任何事情,但我會想象它已經完成了它可以異步執行的一切。你確定你需要把它放在'AsyncTask'中嗎? –
我確定現在你不應該把它放在一個AsyncTask ... ad.loadAd(adRequest)通過admob啓動異步加載,但在Xperia Z1的UI線程上運行該命令大約需要0.5秒,我想你必須忍受那個(?)。 入門:https://firebase.google.com/docs/admob/android/interstitial 示例:https://github.com/googleads/googleads-mobile-android-examples/tree/master/admob/InterstitialExample – CharleyGC