2011-06-10 76 views
1

我在我的应用程序中使用AlarmManager在适当的时间设置闹钟。我在我的应用程序中有多个闹钟,所以每次用户保存一个闹钟时,我都会发现下次应该播放哪个闹钟,并将该闹钟的ID作为一个意图的附加信息传递。这里是我使用的代码:如何更改AlarmManager警报?

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); 

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

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

回答

4

使用FLAG_UPDATE_CURRENT时创建您的PendingIntent

+0

感谢您的答复,我已经改变了我的代码这一点,但它仍然犯规解决it.PendingIntent的PendingIntent =的PendingIntent .getBroadcast(this,56,intent,PendingIntent.FLAG_UPDATE_CURRENT); – Parashar 2011-06-10 20:26:03

+0

它的工作原理是,我没有将广播接收器的价值正确地传递给活动。谢谢你的帮助。 – Parashar 2011-06-15 15:40:10

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;