如何更改AlarmManager警报?

时间:2011-06-10 16:09:24

标签: android android-intent alarmmanager

我在我的应用中使用AlarmManager在适当的时间设置闹钟。我的应用程序中有多个警报,因此每次用户保存警报时,我都会发现下次应该播放哪个警报,并将该警报的ID作为意图的附加内容传递。这是我用于此的代码:

Intent intent = new Intent(this, AlarmBroadcastReceiver.class);
intent.putExtra("alrmId", finalAlr);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 56, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); 
alarmManager.cancel(pendingIntent);
alarmManager.set(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis() + (finalAlrDay * 24 * 60 * 60 * 1000) + (finalAlrHr * 60 * 60 * 1000) + (finalAlrMin * 60 * 1000) + (finalAlrSec * 1000)), pendingIntent);

在这里,如果有任何旧的闹钟设置然后添加新闹钟,我会取消。所有警报都在正确的时间播放,但问题是我在alrmId中设置的intent.putExtra值始终与我第一次设置时的值相同。

例如,如果我第一次设置闹钟,那时alrmId被设置为'1',那么无论我在此之后输入什么值,它总是保持不变。我已经尝试过调试它,并确保intent.putExtra("alrmId", finalAlr)正在输入正确的值,这不是问题所在。有什么问题?

2 个答案:

答案 0 :(得分:4)

创建PendingIntent时使用FLAG_UPDATE_CURRENT

答案 1 :(得分:0)

你也可以使用:

final PendingIntent pendingIntent = PendingIntent.getService(
    contextWeakReference.get(),
    0,
    notificationIntent,
    PendingIntent.FLAG_CANCEL_CURRENT
);

正如文件所说:

   /**
     * Flag indicating that if the described PendingIntent already exists,
     * the current one should be canceled before generating a new one.
     * For use with {@link #getActivity}, {@link #getBroadcast}, and
     * {@link #getService}. <p>You can use
     * this to retrieve a new PendingIntent when you are only changing the
     * extra data in the Intent; by canceling the previous pending intent,
     * this ensures that only entities given the new data will be able to
     * launch it.  If this assurance is not an issue, consider
     * {@link #FLAG_UPDATE_CURRENT}.
     */
    public static final int FLAG_CANCEL_CURRENT = 1<<28;


    /**
     * Flag indicating that if the described PendingIntent already exists,
     * then keep it but replace its extra data with what is in this new
     * Intent. For use with {@link #getActivity}, {@link #getBroadcast}, and
     * {@link #getService}. <p>This can be used if you are creating intents where only the
     * extras change, and don't care that any entities that received your
     * previous PendingIntent will be able to launch it with your new
     * extras even if they are not explicitly given to it.
     */
    public static final int FLAG_UPDATE_CURRENT = 1<<27;