Search code examples
timeradmobhandlerinterstitial

Add interstitial to pdf library


I try to create a book with pdf library i found this library , i created my book everything is ok , i just wanna add interstitial admob and show it every 30 seconds , i tried with handler runnable but it's still show just one time.

mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
handler = new Handler();

final Runnable r = new Runnable() {
    public void run() {
        if (mInterstitialAd.isLoaded()) {
            mInterstitialAd.show();
        }
        handler.postDelayed(this, 1000);
    }
};
handler.postDelayed(r, 1000);

Solution

  • You can use ScheduledExecutorService, and schedule a periodic action.

    mInterstitialAd.setAdListener(new AdListener() {
            public void onAdLoaded() {
                // don't show Ad here
            }
    
            @Override
            public void onAdClosed() {
                createRequest();   //load request whenever ad closed by user
            }
        });
    createRequest();
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    scheduler.scheduleAtFixedRate(new Runnable() {
                public void run() {
    
                      runOnUiThread(new Runnable() {
                          @Override
                          public void run() {
                              if (mInterstitialAd.isLoaded())
                                  mInterstitialAd.show();
                              else
                                  createRequest();
                          }
                      });
                }
            }, 30, 30, TimeUnit.SECONDS);
    

    And createRequest() method

    public void createRequest(){
    
        AdRequest adRequest = new AdRequest.Builder().build();
        mInterstitialAd.loadAd(adRequest);
    }