Following is a simple alarm invoking procedure, note the number of trout I want to catch:
private void setReminder() {
Intent intent = new Intent(this, AlarmReceiver5.class);
int trout = 21;
intent.putExtra("intData", trout);
intent.putExtra("textData",
"Great day for fishing! How many trout you want to get today? ");
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 15 * 1000, sender);
}
When I run it for the first time, the BroadcastReceiver correctly sees that I want to catch 21 trout today.
I changed the number to 22 in Eclipse, run it again, the receiver still sees 21! No matter how I try here, including uninstalling the program from Android, the receiver always gets the old number.
Now if I rename the receiver class from AlarmReceiver5 to AlarmReceiver6, then it can successfully get a different number. But then the same happened again, i.e., no matter how I change the number, the r开发者_运维问答eceiver always gets the old number until I rename the class.
However, if I change the element names in the Bundle (i.e., "intData" and "textData" in the above example), the receiver can't get anything at all! The number becomes 0. Of course I updated the receiver side accordingly.
The above is true even if I used ApiDemo's AlarmController and OneShotAlarm classes.
Now if I tweak the code a little more, I canceled the alarm before setting the next alarm, then the receiver doesn't get anything, the number is 0. See the code below:
private void setReminder() {
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver5.class);
// Cancel the alarm
PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0);
am.cancel(sender);
// Then set it again (using a newly created PendingIntent).
sender = PendingIntent.getBroadcast(this, 0, intent, 0);
int trout = 21;
intent.putExtra("intData", trout);
intent.putExtra("textData",
"Great day for fishing! How many trout you want to get today? ");
sender = PendingIntent.getBroadcast(this, 0, intent, 0);
am.cancel(sender);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 15 * 1000, sender);
}
Can somebody explain what the hack Android AlarmManager is thinking? Thank you! (I may not be able to see your reply for a few hours, because I'm out fishing after posting this.)
in PendingIntent.getBroadcast(this, 0, intent, 0); set the flag parameter (fourth one) to one of the constants in http://developer.android.com/reference/android/app/PendingIntent.html
精彩评论