Android:广告首先加载并在适当的时间到来时显示

时间:2014-01-22 12:39:15

标签: android advertising interstitial

我在showAd()内拨打OnResume来呼叫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);
    }
}   

问题:

广告可以显示出来,但通常会延迟,即当我已经开始其他活动时,它仍然会加载到backgorund中,然后突然广告弹出。我想问一下广告如何首先加载并存储在后台,以便广告只会在我返回此活动时显示?

谢谢!

2 个答案:

答案 0 :(得分:0)

一种方法是打开广告活动,将其置于后台并在其上加载另一个,因此实际上有两个活动,而广告一个在后台加载。这将通过以下方式完成:

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

我不知道这会如何在您的代码中实际运行,因为我不知道延迟有多少,但您可以使用CountDownLatch来同步在后台加载之前显示的广告。 CountDownLatch page就如何将其用作信号量(基本上将其声明为CountDownLatch(1))提供了一个很好的示例。您可以在广告已加载时致电countDown(),这意味着可能已经展示了活动。

答案 1 :(得分:0)

以这种方式应该会更好,就像在谷歌开发者网站上找到的那样: 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();
             }
         }

如果加载成功,则显示,否则直接转到另一个活动。