How to pause interstitial Ads when Android applica

2019-01-26 16:06发布

问题:

I have an issues with interstitial ad using admob for Android, which is the commercial video still running even I tap home button or goes to background. Is there anyone knows how to fix this issue?

I've searched all day long, but couldn't find it. Some says that we can't control the ad. But when Youtube android application is able to pause whenever we tap on Home Button on device or the app goes to background.

回答1:

What version of the AdMob SDK are you using? This solution will work with Google Play Services.

Lets say that this is how you setup your interstitial:

//Here is where you setup your interstitial
//...
adView.setAdListener(new AdListener() {
    @Override
    public void onAdLoaded(){
        adView.show();
    }
});

In your onPause() method you can do the following:

protected void onPause() {
    super.onPause();

    if(adView != null) {
        adView.setAdListener(null);
    }
}

This works because by the time the onPause method is called because of a new interstitial, the ad will already be in the process of being shown and will display normally. However, if onPause() is called because of something else, like the Home button being pressed, it will disable new interstitials from being shown.

Only caveat is if you're using other callback methods available from the AdListener.



回答2:

Declare a global variable

boolean isActivityIsVisible = true;

Update variable base on Activity life cycles

 @Override
protected void onPause() {
    super.onPause();
isActivityIsVisible = false;
}

@Override
protected void onResume() {
    super.onResume();
isActivityIsVisible = true;
}

Check whether Activity is visible in interstitial ads call back, If visible show it.

   mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdClosed() {
            requestNewInterstitial();
        }
        public void onAdLoaded(){
            if (isActivityIsVisible) { mInterstitialAd.show(); }
        }
    });