AdMob ad in onCreate OK, but disappears if you return to activity, why?

陌路散爱 提交于 2019-12-12 03:15:01

问题


I've added an ad to my activity like follows :

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.languageselection);

    // Create the adView
    adView = new AdView(this, AdSize.BANNER, MY_AD_UNIT_ID);

    // Lookup your LinearLayout assuming it�s been given
    // the attribute android:id="@+id/mainLayout"
    LinearLayout layout = (LinearLayout) findViewById(R.id.ad_layout);

    // Add the adView to it
    layout.addView(adView);

    // Initiate a generic request to load it with an ad
    adView.loadAd(new AdRequest());


}

That loads the ad fine. However if I click the menu button and modify some shared preferences and return, the ad has disappeared and doesn't get re-filled.

This is how I navigate out from my activity, notice that I don't call finish on the activity, so the ad that was created in the onCreate should still be there?

@Override
    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.aboutme:
                startActivity(new Intent(this, About.class));
                return true;
            case R.id.help:
                startActivity(new Intent(this, Help.class));
                return true;
            case R.id.preferences:
                startActivity(new Intent(this, EditPreferences.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

How can I ensure an ad doesn't get lost if I navigate away from the activity and return?


回答1:


Personally I create a new AdRequest in onStart():

public void onStart() {
    super.onStart();
    if(adView != null) {
        adView.loadAd(new AdRequest());
    }
}


来源:https://stackoverflow.com/questions/8718233/admob-ad-in-oncreate-ok-but-disappears-if-you-return-to-activity-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!