I tried to create notification in android apps. After I create one transaction, I call "ShowNotification" method to display notification in the device.
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);
}
I can able to see correct message on the notification list of device. When I touch on the notification, I would like to display the message with alert on the screen.
The problem is that it always display last notification in alert box whenever I touch the notification. Below is the code that I wrote in 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) {
}
}
Could anyone of you please suggest me that why it always get last NOtificationID whenver I touch the notification?
I suspect that PendingIntent make overwrite all intent data whenever create new intent.
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
If there any other way not to keep every notification with its notificationId and message?