I'm trying to implement Admob App Open Ads and did exactly what it says on Admob page. But ad doesn't open on app launch but it opens on if app minimized to background and bring back to foreground. I think this is the default Google implementation of app open ads. But I want to make app appear on app launch. Can you help me?
There is 2 classes that makes app open ads work. MyApplication and AppOpenManager classes.
public class MyApplication extends Application {
private static AppOpenManager appOpenManager;
@Override
public void onCreate() {
super.onCreate();
MobileAds.initialize(
this,
initializationStatus -> {});
appOpenManager = new AppOpenManager(this);
}
}
and
/**
* Prefetches App Open Ads.
*/
public class AppOpenManager implements LifecycleObserver,Application.ActivityLifecycleCallbacks {
private static final String LOG_TAG = "AppOpenManager";
private static final String AD_UNIT_ID = "ca-app-pub-7500195269906423/9767523313";
private AppOpenAd appOpenAd = null;
private Activity currentActivity;
private AppOpenAd.AppOpenAdLoadCallback loadCallback;
private final MyApplication myApplication;
private static boolean isShowingAd = false;
/**
* Constructor
*/
public AppOpenManager(MyApplication myApplication) {
this.myApplication = myApplication;
this.myApplication.registerActivityLifecycleCallbacks(this);
ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
}
/** LifecycleObserver methods */
@OnLifecycleEvent(ON_START)
public void onStart() {
showAdIfAvailable();
Log.d(LOG_TAG, "onStart");
}
/** Shows the ad if one isn't already showing. */
public void showAdIfAvailable() {
// Only show ad if there is not already an app open ad currently showing
// and an ad is available.
if (!isShowingAd && isAdAvailable()) {
Log.d(LOG_TAG, "Will show ad.");
FullScreenContentCallback fullScreenContentCallback =
new FullScreenContentCallback() {
@Override
public void onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
AppOpenManager.this.appOpenAd = null;
isShowingAd = false;
fetchAd();
}
@Override
public void onAdFailedToShowFullScreenContent(AdError adError) {}
@Override
public void onAdShowedFullScreenContent() {
isShowingAd = true;
}
};
appOpenAd.setFullScreenContentCallback(fullScreenContentCallback);
appOpenAd.show(currentActivity);
} else {
Log.d(LOG_TAG, "Can not show ad.");
fetchAd();
}
}
/**
* Request an ad
*/
public void fetchAd() {
// Have unused ad, no need to fetch another.
if (isAdAvailable()) {
return;
}
loadCallback =
new AppOpenAd.AppOpenAdLoadCallback() {
/**
* Called when an app open ad has loaded.
*
* @param ad the loaded app open ad.
*/
@Override
public void onAdLoaded(AppOpenAd ad) {
AppOpenManager.this.appOpenAd = ad;
}
/**
* Called when an app open ad has failed to load.
*
* @param loadAdError the error.
*/
@Override
public void onAdFailedToLoad(LoadAdError loadAdError) {
// Handle the error.
}
};
AdRequest request = getAdRequest();
AppOpenAd.load(
myApplication, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback);
}
/**
* Creates and returns ad request.
*/
private AdRequest getAdRequest() {
return new AdRequest.Builder().build();
}
/**
* Utility method that checks if ad exists and can be shown.
*/
public boolean isAdAvailable() {
return appOpenAd != null;
}
/** ActivityLifecycleCallback methods */
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
currentActivity = activity;
}
@Override
public void onActivityStarted(Activity activity) {
currentActivity = activity;
}
@Override
public void onActivityResumed(Activity activity) {
currentActivity = activity;
}
@Override
public void onActivityStopped(Activity activity) {}
@Override
public void onActivityPaused(Activity activity) {}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
@Override
public void onActivityDestroyed(Activity activity) {
currentActivity = null;
}
}
Add this code to your AppOpenManager
import android.app.Activity
import androidx.lifecycle.Lifecycle.Event.ON_START
import android.app.Application
import android.os.Bundle
import android.content.Context
import android.util.Log
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.appopen.AppOpenAd
import java.util.*
class AppOpenManager (private var myApplication: MyApplication) : LifecycleObserver,Application.ActivityLifecycleCallbacks {
companion object {
private const val LOG_TAG = "AppOpenManager"
private const val AD_UNIT_ID = "ca-app-pub-3940256099942544/3419835294"
}
private var appOpenAd: AppOpenAd? = null
private lateinit var loadCallback: AppOpenAd.AppOpenAdLoadCallback
private var currentActivity : Activity? = null
private var isShowingAd : Boolean = false
private var loadTime:Long = 0
private var temp = 0
init{
this.myApplication.registerActivityLifecycleCallbacks(this)
ProcessLifecycleOwner.get().lifecycle.addObserver(this)
}
@OnLifecycleEvent(ON_START)
fun onStart() {
showAdIfAvailable()
Log.d(LOG_TAG, "onStart")
}
fun showAdIfAvailable() {
// Only show ad if there is not already an app open ad currently showing
// and an ad is available.
if (!isShowingAd && isAdAvailable())
{
Log.d(LOG_TAG, "Will show ad.")
val fullScreenContentCallback = object: FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
this@AppOpenManager.appOpenAd = null
isShowingAd = false
fetchAd()
}
override fun onAdFailedToShowFullScreenContent(adError: AdError) {}
override fun onAdShowedFullScreenContent() {
isShowingAd = true
}
}
appOpenAd?.show(currentActivity, fullScreenContentCallback)
}
else
{
Log.d(LOG_TAG, "Can not show ad.")
fetchAd()
}
}
/** Request an ad */
fun fetchAd() {
// We will implement this below.
if (isAdAvailable()) {
return
}
loadCallback = object:AppOpenAd.AppOpenAdLoadCallback() {
/**
* Called when an app open ad has loaded.
*
* @param ad the loaded app open ad.
*/
override fun onAppOpenAdLoaded(ad:AppOpenAd) {
this@AppOpenManager.appOpenAd = ad
this@AppOpenManager.loadTime = (Date()).getTime()
val fullScreenContentCallback = object: FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
// Set the reference to null so isAdAvailable() returns false.
this@AppOpenManager.appOpenAd = null
isShowingAd = false
fetchAd()
}
override fun onAdFailedToShowFullScreenContent(adError: AdError) {}
override fun onAdShowedFullScreenContent() {
isShowingAd = true
}
}
if(temp==0)
{
appOpenAd?.show(currentActivity, fullScreenContentCallback)
temp=1
}
}
/**
* Called when an app open ad has failed to load.
*
* @param loadAdError the error.
*/
override fun onAppOpenAdFailedToLoad(loadAdError: LoadAdError) {
// Handle the error.
}
}
val request : AdRequest = getAdRequest()
AppOpenAd.load(
myApplication, AD_UNIT_ID, request,
AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, loadCallback)
}
/** Creates and returns ad request. */
private fun getAdRequest():AdRequest {
return AdRequest.Builder().build()
}
/** Utility method that checks if ad exists and can be shown. */
fun isAdAvailable():Boolean {
return appOpenAd != null && wasLoadTimeLessThanNHoursAgo(4)
}
/** Utility method to check if ad was loaded more than n hours ago. */
private fun wasLoadTimeLessThanNHoursAgo(numHours:Long):Boolean {
val dateDifference = (Date()).time - this.loadTime
val numMilliSecondsPerHour:Long = 3600000
return (dateDifference < (numMilliSecondsPerHour * numHours))
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStarted(activity: Activity) {
currentActivity = activity
}
override fun onActivityDestroyed(activity: Activity) {
currentActivity = null
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
}
override fun onActivityResumed(activity: Activity) {
currentActivity = activity
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.