我有一个小应用程序,可用于设置未来事件的提醒 . 该应用程序使用AlarmManager来设置提醒用户的时间 . 当闹钟响起时,BroadcastReceiver会对此进行注册,然后启动服务以通过状态栏中的toast和通知通知用户 .
为了在通知和吐司中显示正确的信息,一些额外的信息与意图一起传递 . 第一次注册提醒时,BroadcastReceiver收到并传递给服务的信息是正确的 . 但是对于每个后续提醒(即,BroadcastReceiver接收的每个新意图),即使发送的信息不同,该信息也保持不变 .
例如,如果字符串“foo”作为第一个意图的附加项放置,则广播接收器正确提取“foo” . 如果在第二个意图中将“bar”作为额外内容放置,则广播接收器仍然会提取“foo” .
这是注册警报并传递意图的代码(主要的ui-class):
Intent intent = new Intent(ACTION_SET_ALARM);
intent.putExtra("desc", desc);
intent.putExtra("time", time);
intent.putExtra("dbId", dbId);
intent.putExtra("millis", millis);
PendingIntent pIntent = PendingIntent.getBroadcast(quickAlert.this, 0, intent, 0);
// Schedule the alarm!
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, millis, pIntent);
BroadcastReceiver类中的onReceive()方法:
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, AlertService.class);
String desc = intent.getStringExtra("desc").equals("") ? "": ": " + intent.getStringExtra("desc");
String time = intent.getStringExtra("time");
long dbId = intent.getLongExtra("dbId", -1);
long millis = intent.getLongExtra("millis", -1);
i.putExtra("desc", desc);
i.putExtra("time", time);
i.putExtra("dbId", dbId);
i.putExtra("millis", millis);
Log.d(TAG, "AlertReceiver: " + desc + ", " + time + ", " + dbId + ", " + millis);
Toast.makeText(context, "Reminder: " + desc, Toast.LENGTH_LONG).show();
context.startService(i);
}
清单中的intent-filter:
<receiver android:name=".AlertReceiver">
<intent-filter>
<action android:name="com.aspartame.quickAlert.ACTION_SET_ALARM" />
</intent-filter>
</receiver>
我已经坚持了一段时间了,所以非常感谢帮助!
3 回答
以上答案是正确的,但他们缺乏解释 . 值得注意PendingIntent documentation的这一部分:
请注意"extra"数据具体 not 包含在PendingIntent-identity的概念中!
我在这个主题上找到的最佳链接:http://alvinalexander.com/source-code/android/android-how-attach-extra-intent-pendingintent-notification-solution-example
这是线索:
尝试通过
getBroadcast()
将FLAG_UPDATE_CURRENT添加到PendingIntent
.