set multiple alarms/notifications bug/error?
I'm trying to make an app that allows the user to set tasks and alarms or notifications for each task. I have created a 'setAlarm' method below. However, I have an error that开发者_如何学Go whenever I set multiple tasks with alarms, somehow all the previous ones get cancelled and only the most recently set alarm will go off. Do you know whats the problem? My guess is that the 'calendar' instance gets reset every time I call 'setAlarm'. How could I get around this?
public void setAlarm() {
Intent intent1 = new Intent(NewGoal.this, SingleAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(NewGoal.this,
0, intent1, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
if (alarm_time == 10) {
calendar.add(Calendar.SECOND, alarm_time);
} else if (alarm_time == 30 {
calendar.add(Calendar.SECOND, alarm_time)
}
AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
Log.i(TEST, "In setAlarm method");
Log.i(TEST, "calendar=" + calendar.MILLISECOND);
}
From the documentation:
If there is already an alarm scheduled for the same IntentSender, it will first be cancelled.
May be because you are working with milli second granularity and in Java these is not guaranteed to be accurate. Below is from the JavaDoc. May be you should use System.nanoTime() but this is available only since Java 5. Read this thread on SO: System.currentTimeMillis vs System.nanoTime
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
Also, the below statement from your code is redundant
calendar.setTimeInMillis(System.currentTimeMillis());
@dave.c Thanks, I found this in the documentation too. Here is how I got around it.
final int intent_id= (int) System.currentTimeMillis();
Intent intent1 = new Intent(NewGoal.this, AlarmBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(NewGoal.this, intent_id, intent1, 0);
If there is more than one intent with the same name, the most recent one cancels the previous one. To get around this, use the current time to make each intent different.
Thanks guys.
精彩评论