我有一个小应用程序,可以用来设置将来事件的提醒。该应用程序使用AlarmManager设置用户应被提醒的时间。当闹钟响起时,BroadcastReceiver会注册并启动一个服务来通过Toast和状态栏中的通知来通知用户。
为了在通知和Toast中显示正确的信息,一些额外的信息通过意图传递。第一次注册提醒时,接收BroadcastReceiver并传递给服务的信息是正确的。但对于每个后续提醒(即BroadcastReceiver接收到的每个新意图),即使发送的信息不同,这些信息仍然保持不变。
例如,如果在第一个意图中将字符串"foo"作为额外信息放置,则BroadcastReceiver正确提取"foo"。如果在第二个意图中添加字符串"bar",则BroadcastReceiver仍将提取"foo"。
以下是注册闹钟并传递意图的代码(主UI类):
为了在通知和Toast中显示正确的信息,一些额外的信息通过意图传递。第一次注册提醒时,接收BroadcastReceiver并传递给服务的信息是正确的。但对于每个后续提醒(即BroadcastReceiver接收到的每个新意图),即使发送的信息不同,这些信息仍然保持不变。
例如,如果在第一个意图中将字符串"foo"作为额外信息放置,则BroadcastReceiver正确提取"foo"。如果在第二个意图中添加字符串"bar",则BroadcastReceiver仍将提取"foo"。
以下是注册闹钟并传递意图的代码(主UI类):
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>
我被这个问题困扰了一段时间,非常感谢你的帮助!