admob设置广告请求时间 for Android


您应该将您的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();
    }
}

 

声明:Sandy'Blog|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - admob设置广告请求时间 for Android


一流的吃貨,二流的廚藝,三流的技術,下流的人品