Reputation: 31
i have a problem with Interstitial ad in android. When the application launches, the ad shows and then when the user moves to another activity and returns back to Main Activity, the ad shows again. What should i do that the ad only shows once in Main Activity and never shows again till next restart even if the user move to another activity? Thank you! This is my code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabpmnth_xm);
// Create the interstitial.
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("ca-app-pub-xxxxxxxxxxxx8x/x2xxxxxxxx");
AdRequest aadRequest = new AdRequest.Builder()
.build();
// Begin loading your interstitial.
interstitial.loadAd(aadRequest);
interstitial.setAdListener(new AdListener(){
public void onAdLoaded(){
displayInterstitial();
}
});
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
Upvotes: 1
Views: 125
Reputation: 1449
Create an Application class for your app and do this
public class MyApplication extends Application{
@Override
public void onCreate(){
super.onCreate();
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("ShowInterstitial", TRUE).apply();
}
}
then in your main activity
public void displayInterstitial() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
if (interstitial.isLoaded() && sp.getBoolean("ShowInterstitial", true)){
interstitial.show();
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("ShowInterstitial", false).apply();
}
}
Upvotes: 1