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

查看:245
本文介绍了如果设备重新启动,请启动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?

推荐答案

使用以下代码创建Boot Receiver:

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天全站免登陆