更改alarmmanager使用的pendingintent的意图

时间:2012-12-31 21:48:44

标签: android alarmmanager android-pendingintent

我设置了一些警告:

public void SetAlarm(Context context, int tag, long time){
     AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
     Intent i = new Intent(context, Alarm.class);
     i.putExtra("position", tag);
     PendingIntent pi = PendingIntent.getBroadcast(context, tag, i, PendingIntent.FLAG_CANCEL_CURRENT);
     am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ time, pi); // Millisec * Second * Minute

 }

现在由于某种原因我想更新触发警报的Intent i。我有id(标签)用于识别欲望警报。我怎样才能做到这一点 ?

1 个答案:

答案 0 :(得分:11)

如果您只想更改Intent中的额外内容,可以这样做:

Intent i = new Intent(context, Alarm.class);
// Set new extras here
i.putExtra("position", tag);
// Update the PendingIntent with the new extras
PendingIntent pi = PendingIntent.getBroadcast(context, tag, i,
        PendingIntent.FLAG_UPDATE_CURRENT);

否则,如果您想要更改Intent中的任何其他内容(如操作,组件或数据),则应取消当前警报并创建一个新警报:

AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
// Extras aren't used to find the PendingIntent
PendingIntent pi = PendingIntent.getBroadcast(context, tag, i,
        PendingIntent.FLAG_NO_CREATE); // find the old PendingIntent
if (pi != null) {
    // Now cancel the alarm that matches the old PendingIntent
    am.cancel(pi);
}
// Now create and schedule a new Alarm
i = new Intent(context, NewAlarm.class); // New component for alarm
i.putExtra("position", tag); // Whatever new extras
pi = PendingIntent.getBroadcast(context, tag, i, PendingIntent.FLAG_CANCEL_CURRENT);
// Reschedule the alarm
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ time, pi); // Millisec * Second * Minute