如果设备重新启动,则启动 AlarmManager [英] Start AlarmManager if device is rebooted

查看:37
本文介绍了如果设备重新启动,则启动 AlarmManager的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我想每天在特定时间使用 AlarmManager 运行一些代码.在 android 文档中,我发现了这个:

In my app I want to run some code every day at a specific time using an AlarmManager. In the android documentation I found this:

设备处于睡眠状态时会保留已注册的警报 [...],但如果关闭并重新启动,则会清除.

Registered alarms are retained while the device is asleep [...] but will be cleared if it is turned off and rebooted.

这就是问题所在.即使用户重新启动手机,我也想运行代码.如果用户重新启动手机,他目前必须重新启动我的应用程序才能再次启动警报.我怎样才能防止这种情况?我应该使用更好的机制吗?

And that is the problem. I want to run the code even if the user reboots the phone. If the user reboots the phone he currently has to relaunch my app to start alarms again. How can I prevent this? Is there a better mechanism I should use instead?

推荐答案

使用以下代码创建引导接收器:

Create Boot Receiver using following code :

public class BootBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context pContext, Intent intent) {
        if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
            // Do your work related to alarm manager
        }
    }
}

在您的清单中,注册此广播接收器:

In your Manifest, register this Broadcast receiver :

<receiver
android:name="com.yourapp.BootBroadcastReceiver"
android:enabled="true" >
<intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>

并且不要忘记在 AndroidManifest.xml 中添加权限:

And don't forget to add permission in AndroidManifest.xml :

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

这篇关于如果设备重新启动,则启动 AlarmManager的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆