How To preload AdMob interstitial ad and send to another android activity using intent
Interstitial ads are not meant or built to be passed around like that using intents' extras.
It's better to
- recreate & reload an ad in the next activity
- make an extra public class that holds the interstitial ad, put it there in activity A and retrieve it from there in activity B
Example for 2nd case (semi pseudo code):
public class AdManager {
// Static fields are shared between all instances.
static InterstitialAd ad;
private Context ctx;
public AdManager(Context ctx) {
this.ctx = ctx;
createAd();
}
public void createAd() {
// Create an ad.
ad = new InterstitialAd(ctx);
ad.setAdUnitId(AD_UNIT_ID);
final AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(TEST_DEVICE_ID).build();
// Load the interstitial ad.
ad.loadAd(adRequest);
}
public InterstitialAd getAd() {
return ad;
}
}
Using
Activity A
AdManager adManager = new AdManager();
adManager.createAd();
Activity B
AdManager adManager = new AdManager();
InterstitialAd ad = adManager.getAd();
if (ad.isLoaded()) {
ad.show();
}
Solved this problem by using a singleton design pattern.
/**
* Created by Kirk on 10/26/2017.
*/
public class AdManager {
private static AdManager singleton;
public AdManager() {
}
/***
* returns an instance of this class. if singleton is null create an instance
* else return the current instance
* @return
*/
public static AdManager getInstance() {
if (singleton == null) {
singleton = new AdManager();
}
return singleton;
}
/***
* Create an interstitial ad
* @param context
*/
public static void createAd(Context context) {
interstitialAd = new InterstitialAd(context);
interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
interstitialAd.loadAd(new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build());
}
/***
* get an interstitial Ad
* @return
*/
public static InterstitialAd getAd() {
return interstitialAd;
}
}
in activityA create an load ad
AdManager adManager = AdManager.getInstance();
adManager.createAd(MainActivity.this);
in Activity B retreive and show ad by
AdManager adManager = AdManager.getInstance();
InterstitialAd ad = adManager.getAd();
if (ad.isLoaded()) {
ad.show();
}
InterstitialAd
can be instantiated using any Context
so you could instantiate it (and request ad) during onCreate
of Application
subclass and then later show the ad from anywhere in your code.
This way, you maximise the chances of an ad being loaded by the time you want to show it.
It would be good practice to use an AdManager
(like mentioned in another answer), but not necessary to do so.