Search code examples
androidpush-notificationgoogle-cloud-messagingandroid-pendingintent

GCM message is getting overridden


I 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.

Where have I made a 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);
}

Solution

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