我尝试通过异步任务加载Admob插页式广告,如下所示:
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)
这是否意味着无法通过AsyncTask加载广告,即使任务本身是从UI线程执行的?
如何解决这个问题? MobileAds.initialize, setAdUnitId
执行似乎可以在AsyncTask中使用。我错过了什么吗?不使用AsyncTask时,广告加载正常。可以加载Service
?
答案 0 :(得分:0)
请勿尝试使用AsyncTask
; admob异步加载广告,并包含AdListener
课程,您可以将其扩展为接收onAdLoaded()
,onAdFailedToLoad()
等的回调。请参阅https://developers.google.com/android/reference/com/google/android/gms/ads/package-summary