[英]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. 我的问题是,在项目中打开某个活动后,我初始化了ScheduledExecutorService,每20秒向IntentService类发送一个Intent。
Now when I first open the activity that contains the ScheduledExecutorService, the Intent fires once every 20 seconds as planned. 现在,当我第一次打开包含ScheduledExecutorService的活动时,Intent按计划每20秒触发一次。
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. 这导致Intent在20秒的窗口中发送两次,我认为这与在活动的onResume中创建新的ScheduledExecutorService有关。
How do I ensure that there is only one instance of ScheduledExecutorService at any given time? 如何确保在任何给定时间只有一个ScheduledExecutorService实例?
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. 我建议您在“ Activity
不要这样做,因为它旨在显示UI。 Do that in a Service
instead. 而是在Service
执行此操作。 You can launch a Service
in onStart
and track the state of the executor in your Service
, whether it's launched or not. 您可以启动一个Service
于onStart
和跟踪执行人的状态,你的Service
,无论是推出与否。 Service
is good because it's a background component which is not tied to UI at all. Service
很好,因为它是一个后台组件,完全与UI无关。 It will not be affected during screen rotations etc. 在屏幕旋转等过程中不会受到影响。
You should cancel the previous ScheduledExecutorService
after closing activity: 关闭活动后,您应该取消以前的ScheduledExecutorService
:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.