重新启动后重复警报管理器

我想创建带有通知消息的广播AlarmManager(重复)。我从Pickers中传递日历对象。如果我不重启设备,它将正常工作。但是,当我重新启动设备时,您知道我的calander对象将为null。重新启动后如何管理重复警报以及如何保留日历时间表?感谢您的想法。

public class MyReceiver extends BroadcastReceiver {

private static final int PERIOD = 10000;

final public static String ALARM_ID = "AlarmId";

final public static String NOTIFICATION_ID = "NotificationId";

@Override

public void onReceive(Context ctxt, Intent i) {

}

static void scheduleAlarms(Context ctxt,Calendar c) {

AlarmManager alarManager = (AlarmManager) ctxt

.getSystemService(Context.ALARM_SERVICE);

//notification servise

Intent i = new Intent(ctxt, ScheduledService.class);

i.putExtra(ALARM_ID, 1);

i.putExtra(NOTIFICATION_ID, 1);

PendingIntent pi = PendingIntent.getService(ctxt, 0, i,

PendingIntent.FLAG_UPDATE_CURRENT);

alarManager.setRepeating(AlarmManager.RTC,c.getTimeInMillis(),PERIOD, pi);

}

回答:

您需要使用BroadcastReceiver并将其设置为响应BOOT_COMPLETED消息。例如

在清单中注册您的BroadcastReceiver

<receiver android:name=".MyBootReceiver">

<intent-filter>

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

</intent-filter>

</receiver>

在代码中处理消息

MyBootReceiver.java

public class MyBootReceiver extends BroadcastReceiver

{

private static final String TAG = "MyBootReceiver";

public void onReceive(Context context, Intent intent) {

Log.d(TAG, "onReceive");

Calendar cal = this.getMyCalendar();

this.scheduleAlarms(context, cal);

}

private Calendar getMyCalendar() {

// get your calendar object

}

private void scheduleAlarms(Context ctxt, Calendar c) {

AlarmManager alarManager = (AlarmManager) ctxt.getSystemService(Context.ALARM_SERVICE);

//notification servise

Intent i = new Intent(ctxt, ScheduledService.class);

i.putExtra(ALARM_ID, 1);

i.putExtra(NOTIFICATION_ID, 1);

PendingIntent pi = PendingIntent.getService(ctxt, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

alarManager.setRepeating(AlarmManager.RTC,c.getTimeInMillis(),PERIOD, pi);

}

}

这将在启动时重置您的警报计划。

以上是 重新启动后重复警报管理器 的全部内容, 来源链接: utcz.com/qa/400841.html

回到顶部