GCM message is getting overridden?

2019-02-18 18:35发布

问题:

Hi All am using GCM push notification to pass some notification to the user. my problem is when am sending single message then this works fine if send more than one then the last message is shown to all the notification. Help me on this , were i made mistake ... ??

  private static void generateNotification(Context context, String message) {
  int icon = R.drawable.ic_launcher;
  long when = System.currentTimeMillis();
  NotificationManager notificationManager = (NotificationManager)
          context.getSystemService(Context.NOTIFICATION_SERVICE);

  Intent notificationIntent = new Intent(context, GCMMessageView.class);
  String[] messageArray = message.split("\\#");
  // param :: agentId, Name, Msg
  DatabaseHelper db = new DatabaseHelper(context);
  int notificationId = db.insertnotifications(messageArray[1], messageArray[0], messageArray[messageArray.length-1]);

  notificationIntent.putExtra("message", messageArray[messageArray.length-1]);
  // set intent so it does not start a new activity
  notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
  PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

  Notification notification = new NotificationCompat.Builder(context)
        .setContentText(messageArray[messageArray.length-1])
        .setContentTitle(context.getString(R.string.app_name))
        .setSmallIcon(icon)
        .setWhen(when)
        .setContentIntent(intent)
        .build();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    // Play default notification sound
    notification.defaults |= Notification.DEFAULT_SOUND;

    // Vibrate if vibrate is enabled
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(notificationId, notification);
}

回答1:

Make notification id unique for each message. Due to this, it's being overridden.



回答2:

used this coding in your notification

  int requestID = (int) System.currentTimeMillis();
  PendingIntent intent = PendingIntent.getActivity(context, requestID,
  notificationIntent,0 );

then your notification will not override i hope this will help u



回答3:

Yes agree with Dipo's answer. According to Android Notification Developer Guide This is being overridden due to same notification id for more than one notification.SO the last message is being received on receiver end. You need to Implement random unique Notification id for each notifications. There are number of ways to implement this . You can use this

int notificationId = new Random().nextInt();

You can also use system time in Mili Seconds for Notification id.Then you need to pass this unique Notification ID to notificationManager.notify()

Cheers ! Keep Coding