我希望在活动中加载插页式广告并在其他活动中展示。我找到了这个主题并尝试在第一个答案中执行这些步骤但是有很多错误。
How To preload admob interstitial ad and send to another android activity using intent
我做了什么:
我创建了一个公共类,并将其命名为“AdManager”并将此代码放入其中:
`package com.website.test; import com.google.android.gms.ads.InterstitialAd;public class AdManager {
// Static fields are shared between all instances. static InterstitialAd ad;
public AdManager() { createAd(); }
public void createAd() { // Create an ad. interstitialAd = new InterstitialAd(this); interstitialAd.setAdUnitId("");
AdRequest adRequest = new AdRequest.Builder() .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .addTestDevice(TEST_DEVICE_ID).build(); // Load the interstitial ad. interstitialAd.loadAd(adRequest); } public InterstitialAd getAd() { return ad;}}
在A类的创建活动中,我把它放在:
AdManager adManager = new AdManager();
adManager.createAd();
InterstitialAd ad = admanager.getAd();
if (ad.isLoaded) {
ad.show();
}
但是我附上的图片中有一些错误,请告诉我出了什么问题?
答案 0 :(得分:1)
不要这样做您几乎肯定会泄漏内存并最终导致应用程序崩溃。
图像中的错误是基本的Java语法问题。
图片1
图片2
答案 1 :(得分:1)
class AdManager {
// Static fields are shared between all instances.
private static InterstitialAd interstitialAd;
private static boolean isInterAdsShowed = false;
private Activity activity;
private String AD_UNIT_ID;
AdManager(Activity activity, String AD_UNIT_ID) {
this.activity = activity;
this.AD_UNIT_ID = AD_UNIT_ID;
createAd();
}
void createAd() {
// Create an ad.
interstitialAd = new InterstitialAd(activity);
interstitialAd.setAdUnitId(AD_UNIT_ID);
AdRequest adRequest = new AdRequest.Builder()
//.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
//.addTestDevice(TEST_DEVICE_ID)
.build();
// Load the interstitial ad.
interstitialAd.loadAd(adRequest);
}
static InterstitialAd getAd() {
if(interstitialAd != null && interstitialAd.isLoaded() && !isInterAdsShowed) {
isInterAdsShowed = true;
return interstitialAd;
}
else return null;
}
}
..... 活动A
AdManager adManager = new AdManager(this,"your ads id");
adManager.createAd();
.... 活动B
InterstitialAd ad = AdManager.getAd();
if (ad != null) {
ad.show();
}