我尝试在Android应用中创建通知。在我创建一个交易后,我打电话给#34; 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 Class中编写的代码。
@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和消息保留每个通知?
答案 0 :(得分:0)
我找到了为每个intent添加randon requestCode而不是为每个intent使用0的解决方案。
int requestCode = new Random()。nextInt();
PendingIntent pIntent = PendingIntent.getActivity(this,requestCode,intent,PendingIntent.FLAG_UPDATE_CURRENT);