如何每隔X秒显示插页式广告

时间:2017-12-17 17:38:36

标签: android android-studio ads interstitial

我需要每隔x秒在我的应用中显示插页式广告。我已经封闭了这段代码。它工作正常,但问题是,即使应用关闭,插页式广告仍会显示。

如何在应用关闭时停止播放?

谢谢。

public class MainActivity extends AppCompatActivity {

    private InterstitialAd mInterstitialAd;

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

        prepareAd();

        ScheduledExecutorService scheduler =
                Executors.newSingleThreadScheduledExecutor();

        scheduler.scheduleAtFixedRate(new Runnable() {
            public void run() {
                Log.i("hello", "world");
                runOnUiThread(new Runnable() {
                    public void run() {
                        if (mInterstitialAd.isLoaded()) {
                            mInterstitialAd.show();
                        } else {
                           Log.d("TAG"," Interstitial not loaded");
                        }

                        prepareAd();
                    }
                });
            }
        }, 10, 10, TimeUnit.SECONDS);
    }

    public void  prepareAd() {
        mInterstitialAd = new InterstitialAd(this);
        mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
        mInterstitialAd.loadAd(new AdRequest.Builder().build());
    }
}

1 个答案:

答案 0 :(得分:2)

似乎您的活动位于后台,然后用户可以看到广告,因为一旦您的活动被销毁,您的广告将无法展示,没有this上下文没有活动。

首先:在ScheduledExecutorService

之外保留对onCreate的引用

第二:覆盖onStop并调用scheduler.shutdownNow()

onStop:当您的活动进入后台状态时会调用它

shutdownNow():将尝试停止当前正在运行的任务并停止执行等待任务

因此,即使您的应用处于后台,这也会停止执行者

public class MainActivity extends AppCompatActivity {

    private InterstitialAd mInterstitialAd;
    private ScheduledExecutorService scheduler;
    private boolean isVisible;

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


    @Override
    protected void onStart(){
    super.onStart();
        isVisible = true;
        if(scheduler == null){
            scheduler = Executors.newSingleThreadScheduledExecutor();
            scheduler.scheduleAtFixedRate(new Runnable() {
        public void run() {
            Log.i("hello", "world");
            runOnUiThread(new Runnable() {
                public void run() {
                    if (mInterstitialAd.isLoaded() && isVisible) {
                        mInterstitialAd.show();
                    } else {
                       Log.d("TAG"," Interstitial not loaded");
                    }

                    prepareAd();
                }
            });
        }
    }, 10, 10, TimeUnit.SECONDS);

        }

    }    
    //.. code 

    @Override
    protected void onStop() {
        super.onStop();
        scheduler.shutdownNow();
        scheduler = null;
        isVisible =false;
   }

}