问题
I have created on Chatting Application in Android.
In that I have problem occurs in Push Notification.
Problem is:
- When User A Send Message to User X, so X gets the Push.
- After that User B Send Message to User X, so X gets second the Push.
Then User X clicks on Push of User A Chat Screen not opens, but clicks on Push of User B Chat Screen opens.
How to resolve this.
PendingIntent contentIntent;
UserSessionManager userSession = new UserSessionManager(context);
if (type.equals("2"))
{
if (userSession.getUserSession() != null = PendingIntent.getActivity(
context,
0,
new Intent(context, ChatActivity.class)
.putExtra("to_id", from_id)
.putExtra("username", username)
.putExtra("to_avt", to_avt)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_UPDATE_CURRENT);
}
else
{
contentIntent = PendingIntent.getActivity(context, 0, new Intent(context,
SplashActivity.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT);
}
}
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(Integer.parseInt(from_id), mBuilder.build());
Thanks!!!
回答1:
Your problem is here:
contentIntent = PendingIntent.getActivity(
context,
0,
new Intent(context, ChatActivity.class)
.putExtra("to_id", from_id)
.putExtra("username", username)
.putExtra("to_avt", to_avt)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_UPDATE_CURRENT);
This code overwrites the PendingIntent
every time. So you will only ever have one PendingIntent
(containing the most recent set of "extras").
What you need is to ensure that for each different chat session, you generate a different PendingIntent
. To make the PendingIntent
unique, you can either generate a unique "Intent action" or use a unique requestCode
parameter.
if we assume that from_id
is a unique integer for each session, you could use that as the requestCode
, like this:
contentIntent = PendingIntent.getActivity(
context,
from_id, // unique requestCode
new Intent(context, ChatActivity.class)
.putExtra("to_id", from_id)
.putExtra("username", username)
.putExtra("to_avt", to_avt)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_UPDATE_CURRENT);
or if username
is a unique string, you could use that as the "Intent action" like this:
contentIntent = PendingIntent.getActivity(
context,
0,
new Intent(context, ChatActivity.class)
.setAction(username) // Unique ACTION
.putExtra("to_id", from_id)
.putExtra("username", username)
.putExtra("to_avt", to_avt)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP),
PendingIntent.FLAG_UPDATE_CURRENT);
either of these solutions will ensure that you generate a separate PendingIntent
for each session.
来源:https://stackoverflow.com/questions/28292560/push-notification-not-works-properly