我可以使用哪些选项来检查 IntentService 是否已在运行?
我有一个 AlarmService,它每 15 分钟唤醒一次并触发 IntentService。但是,我想确保如果先前启动的 IS 已经在运行,则 AlarmService 不会尝试启动另一个 IS(IS 正在处理文件,如果第二个版本尝试启动,则会出现奇怪的竞争条件)作用于相同的文件)。
轮询系统以查看我的 IS 实例是否已在运行并跳过 AlarmService cron 的当前迭代的最佳方法是什么?
I have an AlarmService that wakes up every 15 minutes and fires off an IntentService. However, I would like to make sure that if a previously started IS is already running, that the AlarmService doesn't try to start another one (the IS is dealing with files and there would be an odd race condition if a second version tried to act on the same files).
What's the best way to poll the system to see if an instance of my IS is already running and just skip the current iteration of the AlarmService cron?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不会有竞争条件。首先,
IntentService
只会有一个实例。其次,IntentService
在onHandleIntent()
中一次只会处理一个Intent
。不要那样做。在您的
IntentService
中,跟踪您上次在数据成员中进行操作的时间。如果在onHandleIntent()
中,该值为null
,那么这是您一段时间以来第一次经过,因此您可能想继续执行该工作。如果该值不为null
,则将其与当前时间进行比较,如果太早,则从onHandleIntent()
返回。There will be no race condition. First, there will only ever be one instance of the
IntentService
. Second, theIntentService
will only process oneIntent
at a time inonHandleIntent()
.Don't do it that way. In your
IntentService
, track the last time you did work in a data member. If, inonHandleIntent()
, that value isnull
, it's your first pass through in a while, and so you probably want to go ahead and do the work. If the value is notnull
, compare it to the current time, and if it's too soon, just return fromonHandleIntent()
.