Android - 每天凌晨 4 点运行一个服务

发布于 2024-09-05 05:02:11 字数 278 浏览 2 评论 0原文

我想了解每天凌晨 4 点运行服务的最佳实践。

我认为我应该这样做的方式是使用 AlarmManager 创建一个新的重复警报并让它在凌晨 4 点运行该服务。问题是,我不确定在哪里放置设置警报的代码。

我是否在主要活动中将其作为 OnCreate 方法中的首要任务之一来执行?我是否用 BroadcastReceiver 和意图做了一些时髦的事情?当用户更新我的应用程序时会发生什么?当用户重新启动时会发生什么?

任何有关这些问题的帮助将不胜感激:) 示例代码也会很有帮助!

巴拉

I would like to know the best practices for running a Service every day at 4AM.

The way I think I should be doing it is to create a new repeating alarm using AlarmManager and having it run the service at 4AM. Problem is, I'm not sure where to put the code to set the alarm.

Do I do it in my main activity as one of the first tasks in the OnCreate method? Do I do some funky stuff with BroadcastReceivers and intents? What happens when a user updates my app? What happens when a user restarts?

Any help with these questions would be much appreciated :) Sample code would be helpful as well!

Bara

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

旧瑾黎汐 2024-09-12 05:02:11

您可以在每次手机启动和每次应用程序启动时安排闹钟。要监听手机启动事件,您可以使用 BroadcastReceiver。

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
.
.
.
<receiver android:name=".BootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

如需完整示例,您可以查看 Photostream 应用程序 http://code.google。 com/p/apps-for-android。它使用完全相同的方法。

You can schedule your alarm each time phone boots and each time your application starts. To listen to phone boot event you can use BroadcastReceiver.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
.
.
.
<receiver android:name=".BootReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

For a complete sample you can take a look at Photostream application http://code.google.com/p/apps-for-android. It uses exactly the same approach.

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