重启后重复警报管理器

时间:2013-07-30 07:59:24

标签: android android-service android-broadcast

我想用通知消息创建广播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);
}

1 个答案:

答案 0 :(得分:12)

您需要使用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);
    }
}

这将在启动时重置您的闹钟计划。