如何取消ScheduledExecutorService / Runnable以便在回压/退出活动时停止加载InterstitialAd

时间:2018-12-03 04:16:16

标签: java android admob

我只想在一个特定的时间只显示一次InterstitialAd。但是在执行InterstitialAd加载方法之前,如果用户向后按下活动并退出活动,则ScheduledExecutorService或Runnable方法应该完全停止,但它正在后台运行,并且在特定时间显示InterstitialAd。如何停止在以下代码中显示InterstitialAd。谢谢。

public class CustomActivity 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");
                        }



                    }
                });

            }
        }, 30, 1, TimeUnit.SECONDS);

     }


    public void  prepareAd(){

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

 @Override
    public void onBackPressed() {
       super.onBackPressed();
        finish();
    }
}

1 个答案:

答案 0 :(得分:0)

有一个关于活动的方法isFinishing(),用于确定活动是否仍在运行,或者是否已从其上销毁或调用了finish()

如果返回true,则可以显示广告;如果为false,则取消计划程序。

示例

           public void run() {

                    if (!isFinishing() && mInterstitialAd.isLoaded()) {

                        mInterstitialAd.show();
                    } else if(isFinishing()){

                        scheduler.shutdown();
                    }
                    else{
                        Log.d("TAG"," Interstitial not loaded");   
                    }

                }