admob设置广告请求时间 for Android

2017年10月27日 750点热度 0人点赞 0条评论

您应该将您的admob生命周期附加到您的活动生命周期,以便您的应用程序对用户可见时,您可以开始/停止显示添加。
为您创建广告和处理程序的全局变量

private InterstitialAd mInterstitialAd;

private Handler mHandler = new Handler();

private Runnable mRunnable = new Runnable() {
    @Override
    public void run() {

        // Wait 60 seconds
        mHandler.postDelayed(this, 60*1000);

        // Show Ad
        showInterstitial();

    }
};

然后

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create the InterstitialAd and set the adUnitId
    mInterstitialAd = newInterstitialAd();
    loadInterstitial();

}

@Override
protected void onStart() {
    super.onStart();
    // Start showing Ad in every 60 seconds 
    //when activity is visible to the user
    mHandler = new Handler();
    //mHandler.post(mRunnable);

    // Run first add after 20 seconds
    mHandler.postDelayed(mRunnable,20*1000);
}

protected void onStop() {
    super.onStop();
    // Stop showing Ad when activity is not visible anymore
    mHandler.removeCallbacks(mRunnable);
}

private void loadInterstitial() {
    AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice("SEE_YOUR_LOGCAT_TO_GET_YOUR_DEVICE_ID")
            .setRequestAgent("android_studio:ad_template").build();
    mInterstitialAd.loadAd(adRequest);
}

private InterstitialAd newInterstitialAd() {

    InterstitialAd interstitialAd = new InterstitialAd(this);
    interstitialAd.setAdUnitId(getString(R.string.interstitial_ad_unit_id));
    interstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            mNextLevelButton.setEnabled(true);
        }

        @Override
        public void onAdFailedToLoad(int errorCode) {
            mNextLevelButton.setEnabled(true);
        }

        @Override
        public void onAdClosed() {

            // Reload ad so it can be ready to be show to the user next time 
            mInterstitialAd = newInterstitialAd();
            loadInterstitial();

        }
    });
    return interstitialAd;

}

private void showInterstitial() {
    // Show the ad if it's ready. Otherwise toast and reload the ad.
    if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    } else {
        Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
        mInterstitialAd = newInterstitialAd();
        loadInterstitial();
    }
}

 

Sandyliao

保持飢渴好吃的性格、維持好攝之徒的愛好、繼續在三流的技術下活著!

文章评论

您需要 登录 之后才可以评论