0

I am calling showAd()inside OnResume to call for interstitialAd.

ShowAd()

public void showAd()   
{   
    SavedFrequency = getSharedPreferences("adfreq", MODE_PRIVATE);
    AdfrequencyInt = SavedFrequency.getInt("adfreq", 0);
    AdfrequencyInt++;
    if (AdfrequencyInt > 59) 
    {
        AdfrequencyInt = 0;
    }
    Toast.makeText(this, ""+AdfrequencyInt, Toast.LENGTH_SHORT).show(); 
    SharedPreferences.Editor preferencesEditorF1 = SavedFrequency.edit();
    preferencesEditorF1.putInt("adfreq", AdfrequencyInt);
    preferencesEditorF1.apply();

    if (AdfrequencyInt % 10 == 0) 
    {
        interstitialAd = new InterstitialAd(this, MY_PUBLISHER_ID); // Create an ad
        interstitialAd.setAdListener(this); // Set the AdListener.
        AdRequest adRequest = new AdRequest();
        adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
        interstitialAd.loadAd(adRequest);
    }
}   

Question:

The ad can be shown out, but is usually delayed, i.e. when I have already started off another activity, it is still loading in the backgorund and then suddenly the ad pops out. I would like to ask how could the ad be loaded first and stored in the background such that the ad will only be shown when I return to this activity?

Thanks!

pearmak
  • 4,979
  • 15
  • 64
  • 122

2 Answers2

0

One way would be opening the Ad Activity, put it in background and load another one over it, so actually there are two activities and the Ad one loading in the background. This would be done with:

final Intent intent = new Intent(this, AnotherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);  

I don't know how would this actually work in your code as I don't know how much that delay is, but you could use a CountDownLatch to synchronize the Ad showing before the background loading. The CountDownLatch page has a good example on how to use it as a semaphore (basically, declaring it as CountDownLatch(1)). You could simply call countDown() when the ad is already loaded and that would mean that Activity may already be shown.

nKn
  • 13,691
  • 9
  • 45
  • 62
0

It should be better in this way, as found in the Google Developer site: http://developer.android.com/reference/com/google/android/gms/ads/InterstitialAd.html

     mNextLevelButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             // Show the interstitial if it is ready. Otherwise, proceed to the next level
             // without ever showing it.
             if (mInterstitialAd.isLoaded()) {
                 mInterstitialAd.show();
             } else {
                 // Proceed to the next level.
                 goToNextLevel();
             }
         }

If it is loaded successful, then show, else directly go to another activity.

pearmak
  • 4,979
  • 15
  • 64
  • 122