Reputation: 171
i am making android app with AdMob Integrated in my app , i am using AdMob to show ad after 20 seconds of WebView loaded. the problem is when user close the app before 20 seconds Interstitial ads still show, which is against the google AdMob policy, how can i make that when user exit the activity or app , Interstitial ad should not be display
this is my code:
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
interAd = new InterstitialAd(MainActivity.this);
interAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
interAd.loadAd(adRequest);
interAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
interAd.show();
}
});
interAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
// Code to be executed when the interstitial ad is closed.
Log.i("Ads", "onAdClosed");
}
});
}
} , 20000);
Upvotes: 1
Views: 3194
Reputation: 989
Add onBackpress and onDestroy overides and remove your handlers callbacks and set the interstitialad variable to null in each of them.
@Override
protected void onBackpressed() {
handler.removeCallbacks(your handler name here);
interAd =null
super.onBackpressed();
}
@Override
protected void onDestroy() {
handler.removeCallbacks(your handler name here);
interAd =null
super.onDestroy();
}
If you want to also handle this if your app goes in background then add onPause overide too.
@Override
protected void onPause() {
handler.removeCallbacks(your handler name here);
interAd =null
super.onPause();
}
Hope that helps.
Let me know if you need further assistance.
Upvotes: 0
Reputation: 2045
Just pass your handler when onDestroy called
Handler myHandler = new Handler().postDelayed(new Runnable() {
@Override
public void run() {
interAd = new InterstitialAd(MainActivity.this);
interAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
.build();
interAd.loadAd(adRequest);
interAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
if(interAd.isLoaded() && interAd !=null)
interAd.show();
}
});
interAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
// Code to be executed when the interstitial ad is closed.
Log.i("Ads", "onAdClosed");
}
});
}
} , 20000);
@Override
protected void onDestroy() {
Log.d("MainActivty","onDestroy removing callbacks...");
handler.removeCallbacks(myHandler);
interAd =null
super.onDestroy();
}
Upvotes: 1