闹钟管理器即使在重启后是否还会继续存在?

57

我是个android的新手,一直在研究闹钟。我想要在生日那天提醒。我已经使用了Alarm Manager,但看到有些人说它会在重启后清除,这让我很困惑。由于没有安卓手机,所以我只能使用模拟器。

以下是我的代码:

public void schedAlarm() {
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent intent = new Intent(this, AlarmService.class);
    pendingIntent = PendingIntent.getBroadcast(this, contact.id, intent, PendingIntent.FLAG_ONE_SHOT);
    am.setRepeating(AlarmManager.RTC, timetoAlarm, nextalarm, pendingIntent);
}

我用这个BroadcastRecever代替了AlarmSerivce,代码如下:

public void onReceive(Context context, Intent intent) {
    nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    CharSequence from = "It Birthday!";
    CharSequence message =" Greet your friend.";
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
    Notification notif = new Notification(R.drawable.ic_launcher, "Birthday", System.currentTimeMillis());
    notif.setLatestEventInfo(context, from, message, contentIntent);
    nm.notify(1, notif);
 }

这足够了吗?


1
默认情况下,设备关闭时所有的闹钟都会被取消。https://developer.android.com/training/scheduling/alarms#boot - AZ_
3个回答

104
一个简单的回答是不行。但是,您可以通过创建一个BroadCastReceiver来实现此目的,在设备引导完成时启动报警器。

在BroadCastReceiver类中使用<action android:name="android.intent.action.BOOT_COMPLETED" />来捕获引导活动。

您需要将上述行添加到AndroidManifest.xml中,如下所示:

<receiver android:name=".AutoStartUp" android:enabled="true" android:exported="false" android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
     <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
    </receiver>

1
我能否将AlarmService直接改为BroadCastReceiver? - Xelamae
1
@Lucifer - 安卓系统在重启后会清除我们设置的所有闹钟吗?如果是,那么我们需要在重启后重新设置它们! - Behzad
1
@Behzad,是的,如果警报是由代码设置的,那么在重新启动时它肯定会被清除。 - Lucifer
29
请注意,在您的清单文件中还需要请求RECEIVE_BOOT_COMPLETED权限。 - Hal
5
在接收到启动事件后,我是否需要重新在此接收器中注册所有的闹钟? - Darpan
显示剩余3条评论

13

是的,即使在重新启动后也可以使AlarmManager工作。也许这是最简单的方法:将以下代码添加到您的AndroidManifest.xml中:

<receiver android:name=".AlarmReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

不要忘记在AndroidManifest.xml文件中包括用户权限:

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

3
即使定时器设置了一个小时后,它在重新启动后会自动触发。 - ralphgabb
1
通常情况下,这将在一段时间后调用.AlarmReceiverPendingIntent之后被称为。通过添加BOOT_COMPLETEDQUICKBOOT_POWERON。在上面的答案中,.AlarmReceiver在启动时被调用(错误的操作),并且PendingIntent在启动后仍然丢失。相反,应该从BOOT_COMPLETEDQUICKBOOT_POWERON调用另一个接收器,以重新初始化PendingIntent - Aaron Dougherty

3

在某些手机上,只添加

<action android:name="android.intent.action.Boot_COMPLETED" />

无法工作,您还需要添加

<action android:name="android.intent.action.QUICKBOOT_POWERON" />

连同之前的内容一起


后者的文档呢?在developer.android.com上没有找到... - Mitulát báti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接