简体   繁体   中英

How to prevent multiple ScheduledExecutorServices from being created upon reopening activity

My issue is that upon opening a certain activity in my project, I initialize a ScheduledExecutorService that sends an Intent to an IntentService class every 20 seconds.

Now when I first open the activity that contains the ScheduledExecutorService, the Intent fires once every 20 seconds as planned.

The issue arises when I exit the activity (staying in the app) and then reenter the activity. This results in the Intent being sent twice in a 20 second window, and I figure it has to do with my creating a new ScheduledExecutorService in the onResume of my activity.

How do I ensure that there is only one instance of ScheduledExecutorService at any given time?

Relevant code is below:

@Override
    public void onResume() {
        super.onResume();

        ScheduledExecutorService scheduleIntentSender = Executors.newScheduledThreadPool(1);
        scheduleIntentSender.scheduleAtFixedRate(new Runnable() {
            public void run() {
                sendIntent();
            }
        }, 0, 20,TimeUnit.SECONDS);

        mDownloadStateReceiver =
                new DownloadStateReceiver();
        // Registers the DownloadStateReceiver and its intent filters
        LocalBroadcastManager.getInstance(this).registerReceiver(
                mDownloadStateReceiver,
                testIntentFilter);
    }

I suggest not doing that in your Activity because it's intended to display a UI. Do that in a Service instead. You can launch a Service in onStart and track the state of the executor in your Service , whether it's launched or not. Service is good because it's a background component which is not tied to UI at all. It will not be affected during screen rotations etc.

You should cancel the previous ScheduledExecutorService after closing activity:

 ScheduledExecutorService scheduleIntentSender = Executors.newScheduledThreadPool(1);
   final ScheduledFuture schedulHandler = scheduleIntentSender.scheduleAtFixedRate(new Runnable() {
        public void run() {
            sendIntent();
        }
    }, 0, 20,TimeUnit.SECONDS);
//Call schedulHandler.cancel(true) to cancel scheduleIntentSender in onDestroy()

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