延迟操作和 BroadcastReceiver
我遇到的情况是,我必须在设备连接电源后N 秒启动一些非 UI 操作。用户也可以通过 UI 启动该操作。
我在 AndroidManifest.xml 中定义了一个 BroadcastReceiver,它监听 ACTION_POWER_CONNECTED。
我有一项对 onStartCommand 执行所需操作的服务。我的问题是 - 当广播触发操作时启动该服务的正确方法是什么?
我有两个选择:
一次性计时器任务。但是我认为这可能是错误的,因为根据文档,我无法从 BroadcastReceiver 启动任何异步任务。
重新设计服务:
- 如果用户触发了操作,则在 onStartCommand 处启动操作
- 启动计时器任务并在计时器拍摄时执行操作 - 与 1 中的逻辑相同。但在服务内部 - 如果操作是由广播触发的。
我倾向于2。它会使代码变得更复杂一些,但似乎这是唯一正确的方法。
-列弗
I have a case in which I have to start some non-UI action N seconds after power has been connected to the device. That action could be also started by user via UI.
I have a BroadcastReceiver defined in AndroidManifest.xml which listens for ACTION_POWER_CONNECTED.
I have a service that does required action on onStartCommand. My question is - what is the right way to start that service in case of when action is triggered by broadcast?
I have two options in mind:
One-shot timer task. However I think it might be wrong because of according to docs, I could't start any async tasks from BroadcastReceiver.
Redesign service:
- start action at onStartCommand, if action was triggered by user
- start timer task and do action at timer shot - same logic as in 1. but inside service - if action was triggered by broadcast.
I am inclined to 2. It will make code a bit more complex, but it seems it is only right way.
-Lev
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的方法是#2。这是因为一旦您离开,
onReceive
应用程序进程可能会被终止。在这种情况下,您的 TimerTask 将无济于事。作为替代解决方案,请使用
AlarmManager
和它的set
函数来安排待处理的服务意图。这可能是您的情况的最佳解决方案。The correct way is #2. That's because as soon as you leave
onReceive
application process might be killed. And yourTimerTask
won't help in such case.As an alternative solution, use
AlarmManager
and itsset
function to schedule pending service intent. This is probably the best solution in your case.