简体   繁体   中英

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

I want to display InterstitialAd only once at a particuar time.But before executing the InterstitialAd load method if the user back press the activity and exit the activity the ScheduledExecutorService or Runnable method should stop completely, but it is running in the background and displays the InterstitialAd at particular time . How to Stop to display the InterstitialAd in the following code.Thank you.

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();
    }
}

There is method on activity, isFinishing() , which determines if activity is still running or has been destroyed or called finish() on from.

If it returns true, you can show ad, If false, cancel the scheduler.

Example

           public void run() {

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

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

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

                } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM