【发布时间】:2016-10-03 02:46:41
【问题描述】:
我尝试在 Android 应用中创建通知。创建一个事务后,我调用“ShowNotification”方法在设备中显示通知。
public void showNotification(String screen, String message) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("screen", screen);
intent.putExtra("message",message);
int id = 1;
try {
// get latest id from SQLite DB
id = DbManager.getInstance().getIntDbKeyValue("notif_id");
if (id < 1) {
id = 1;
}
} catch (Exception e) {
}
intent.putExtra("notif_id", id + "");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification n = new Notification.Builder(this).setContentTitle(getString(R.string.app_name)).setContentText(message)
.setSmallIcon(R.drawable.ic_launcher).setContentIntent(pIntent).setAutoCancel(true)
.setStyle(new Notification.BigTextStyle().bigText(message))
.build();
// set next running id into SQLite DB
DbManager.getInstance().setDbKeyValue("notif_id", (id + 1) + "");
notificationManager.notify(id, n);
}
我可以在设备的通知列表中看到正确的消息。 当我触摸通知时,我想在屏幕上显示带有警报的消息。
问题是每当我触摸通知时,它总是在警报框中显示最后一个通知。下面是我在 MainActivity 类中写的代码。
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
try {
checkIntent(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
private void checkIntent(Intent intent) {
try {
int id = Integer.parseInt(intent.getStringExtra("notif_id"));
if (id > 0 ) {
String s = intent.getStringExtra("screen");
if ("XXXXXX".equalsIgnoreCase(s)) {
Fragment f = new MonitoringFragment();
Bundle bundle = new Bundle();
bundle.putString("message", intent.getStringExtra("message"));
f.setArguments(bundle);
showFragment(f, false);
}else{
showFragment(new XxxxFragment(), false);
}
}
} catch (Exception e) {
}
}
谁能告诉我为什么每次我触摸通知时它总是得到最后一个NOtificationID?
我怀疑 PendingIntent 会在创建新意图时覆盖所有意图数据。
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
如果有任何其他方法不保留每个通知及其 notificationId 和消息?
【问题讨论】:
-
在保存和检索通知键值时一定存在逻辑错误,您可以用调试器检查通知键是否每次都在增加。