延迟操作和 BroadcastReceiver

发布于 2024-11-19 13:53:21 字数 603 浏览 2 评论 0原文

我遇到的情况是,我必须在设备连接电源后N 秒启动一些非 UI 操作。用户也可以通过 UI 启动该操作。

我在 AndroidManifest.xml 中定义了一个 BroadcastReceiver,它监听 ACTION_POWER_CONNECTED

我有一项对 onStartCommand 执行所需操作的服务。我的问题是 - 当广播触发操作时启动该服务的正确方法是什么?

我有两个选择:

  1. 一次性计时器任务。但是我认为这可能是错误的,因为根据文档,我无法从 BroadcastReceiver 启动任何异步任务。

  2. 重新设计服务:

    • 如果用户触发了操作,则在 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:

  1. 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.

  2. 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

若有似无的小暗淡 2024-11-26 13:53:21

正确的方法是#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 your TimerTask won't help in such case.

As an alternative solution, use AlarmManager and its set function to schedule pending service intent. This is probably the best solution in your case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文