create preload ad code example

Example: admob preload ad

**
* Created by Kirk-Patrick Brown 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;
}
}

//create in activity A
 AdManager adManager = AdManager.getInstance();
    adManager.createAd(MainActivity.this);

//show in activity B
 AdManager adManager = AdManager.getInstance();
    InterstitialAd ad =  adManager.getAd();

    if (ad.isLoaded()) {
        ad.show();
    }

Tags:

Java Example