0

I have tried for setting Admob Ads but it's showing every time when I clicked back button. I want the same when I clicked the back button 4-5 times

@Override
public void onBackPressed() {
    showAdvertisement();
}

private void showAdvertisement() {
    if (mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    } else {
        finish();
    }
}

private void loadInterstitialAd() {
    AdRequest adRequest = new AdRequest.Builder()
            .build();

    mInterstitialAd.loadAd(adRequest);
}

sanoJ
  • 2,935
  • 2
  • 8
  • 18
  • 1
    From your code it is pretty obvious why the add is always being shown. You need to implement some logic in `onBackPressed` that counts the amount of taps the user has made and that based on that calls either `finish()` or `showAdvertisement()` – Nicolás Carrasco-Stevenson Jul 23 '19 at 06:26
  • you want to load advertisement when back button is clicked 5 times, but when do you want to finish your activity ? On 6th time or something else. – ChandraShekhar Kaushik Jul 23 '19 at 06:26
  • Use a shared preference to store a count. Here is an [example](https://stackoverflow.com/a/23024962/9263083) – sanoJ Jul 23 '19 at 06:26
  • You can store a `shared/static counter` and increase that counter whenever backbutton press. If the count reach 5 times then call `showAdvertisement();` – MD Ruhul Amin Jul 23 '19 at 06:29
  • Can you help me where I have to use the same in my code....Please help me with code – Harshal Gadakh Jul 23 '19 at 06:32
  • You could also consider having a 20% chance of showing the ad when you backpress, which would be simple, you'd just add `ThreadLocalRandom.current().nextInt(5) == 0` to your condition. – PPartisan Jul 23 '19 at 06:35

2 Answers2

1

There are two simple options:

1) Store an integer in shared preferences that represents the number of times the back button was pressed, whenever the user pressed it increment it by one, before calling show advertisement check if the saved value module (%) 5 is equal to 0.

2) Create a field of count and set it to 0, increment it by one and again check if the count module 5 equal to 0

I would go with the second option if you don't need to store the number of times pressed.

Gal
  • 422
  • 5
  • 21
1

Simple and easy way is here.look below code ;)

int counter=0;
    @Override
    public void onBackPressed()
    {
        counter++;
        if(counter==5)
        {
            showAdvertisement();
            counter=0;
        }
    }
niceumang
  • 1,347
  • 1
  • 8
  • 21