簡體   English   中英

如何取消ScheduledExecutorService / Runnable以便在回壓/退出活動時停止加載InterstitialAd

[英]How to cancel ScheduledExecutorService/ Runnable to stop loading the InterstitialAd on backpress/exit the activity

我只想在特定時間只顯示一次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();
    }
}

活動上有一個方法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");   
                    }

                } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM