java – How to time an Interstitial ad?

Question:

How to time an Interstitial ad?

Example: I want that when opening the app, the ad is displayed within 5 seconds, if not, the display will be canceled and the app proceed to the main Activity.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    interstitialAd = new InterstitialAd(Main.this);
    interstitialAd.setAdUnitId(getString(R.string.adMobInter));
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .addTestDevice(getString(R.string.adMob_test))
            .build();
    interstitialAd.loadAd(adRequest);

    interstitialAd.setAdListener(new AdListener() {


        @Override
        public void onAdLoaded() {
            
               displayInterstitial();
            
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            
            onMain();


        }

        @Override
        public void onAdClosed() {
            
            onMain();

        }
    });

}

public void displayInterstitial() {
  
    if (interstitialAd.isLoaded())  {
        interstitialAd.show();

    }
}

public void onMain() {

    setContentView(R.layout.main); }
   

Answer:

Speak Francis,

Try to do it that way then:

interstitialAd.setAdListener(new AdListener() {

    public void onAdLoaded() {
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
        public void run() { 

           @Override
           public void onReceiveAd() {
             //Abriu, ta beleza
           }

           @Override
           public void onFailedToReceiveAd(){
            //Dificuldades para abrir
            startActivity();
           }

           @Override
           public void onAdClosed(){
              Log.d("AD Closed", "Ad closed");
              startActivity();
           }

        } 
    }, 5000);
}

});

5 seconds of delay will pass, if it falls into onReceiveAd() it is because it opened normally, and after being displayed and closed it will fall into onAdClosed(), then just send the user to the app's home screen.

If the 5 seconds pass and the ad has not yet loaded, the user will fall into onFailedToReceiveAd(), then just send it to the app's home screen, in the same way as onAdClosed().

Hugs.

Scroll to Top
AllEscort