android-studiohandlerandroid-handlerinterstitialfacebook-audience-network

Show interstitialAd after 30 seconds Audience Network Facebook


I want to use Facebook Audience Network for my Android app, I have integrated interstitialAd in-app and it works fine but it appears as Activity launch. I want to show ad after 30 seconds. this is my code

 interstitialAd = new InterstitialAd(this, "1555910157949688_1556058954601475");

    interstitialAd.setAdListener(new InterstitialAdListener() {
      

        @Override
        public void onAdLoaded(Ad ad) {
            // Interstitial ad is loaded and ready to be displayed
            Log.d(TAG, "Interstitial ad is loaded and ready to be displayed!");
            // Show the ad
            interstitialAd.show();
        }

       
    });

    interstitialAd.loadAd();

and I have tried this to schedule my ad but it did not work.

private void showAdWithDelay() {
   Handler handler = new Handler();
   handler.postDelayed(new Runnable() {
       public void run() {
            // Check if interstitialAd has been loaded successfully
           if(interstitialAd == null || !interstitialAd.isAdLoaded()) {
               return;
           }
            // Check if the ad is already expired or invalidated, and do not show ad if that is the case. You will not get paid to show an invalidated ad.
           if(interstitialAd.isAdInvalidated()) {
               return;
           }
           // Show the ad
            interstitialAd.show(); 
       }
   }, 3000); 
}

Solution

  • I prefer to do this:

          Handler handler = new Handler();
          interstitialAd = new InterstitialAd(this, "XXX");
          interstitialAd.setAdListener(new InterstitialAdListener() {
            @Override
            public void onAdLoaded(Ad ad) {
              handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                  interstitialAd.show();
                }
              }, YOUR_TIME);
            }
          });
    
          interstitialAd.loadAd();
    

    And if you want to be more precise, do it:

          final long lastTime = System.currentTimeMillis();
          Handler handler = new Handler();
          interstitialAd = new InterstitialAd(this, "XXX");
          interstitialAd.setAdListener(new InterstitialAdListener() {
            @Override
            public void onAdLoaded(Ad ad) {
              long now = System.currentTimeMillis();
              long timeWait;
              if (now - lastTime >= YOUR_TIME){
                timeWait = 0;
              }else {
                timeWait = YOUR_TIME-(now-lastTime);
              }
              handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                  interstitialAd.show();
                }
              }, timeWait);
            }
          });
    
          interstitialAd.loadAd();