Notifications will be overwritten by each other

I send different notifications. But when you click on any of them, I get the data that was sent to the last notification. How to fix it? I need to note that everyone stores their data, and a new notification does not replace them. I use the flag PendingIntent.FLAG_UPDATE_CURRENT, but I also use all the flag suggestions.

private void generateNotification(Context context, String title, String message,int groupid,Intent data) {

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
        Intent intent = new Intent(context,MyActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        if (groupid==1){
            intent.putExtra("guest",data.getStringExtra("guest"));
            intent.putExtra("hotel",data.getStringExtra("hotel"));
            intent.putExtra("room",data.getStringExtra("room"));
        }
        if (groupid==5){
            intent.putExtra("hotel",data.getStringExtra("hotel"));
        }
        if (groupid==4){
            intent.putExtra("hotel",data.getStringExtra("hotel"));
            intent.putExtra("guest",data.getStringExtra("guest"));
        }

        intent.putExtra("group_id",groupid);
        Log.d("mylogout","group_id: "+groupid);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification notification   = new NotificationCompat.Builder(context)
                .setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.ic_stat_gcm)
                .setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_stat_gcm))
                .setTicker(" ")
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setContentTitle(title)
                .setContentText(message)
                .build();
        notificationManager.notify(ID_NITIF++, notification);
    }
+4
source share
1 answer

The trick is to add another requestCodeto the PendingIntent for each different notification.

Documentation:

public static PendingIntent getActivity ( , int requestCode, , int)

PendingIntents, , , , . , requestCode .

, , :

//Use the hashcode of current timestamp mixed with some string to make it unique 
int requestCode = ("someString" + System.currentTimeMillis()).hashCode();

//Also add it to the intent, to make sure system sees it as different/modified
intent.putExtra("randomRequestCode", requestCode);

//Add the requestCode to the PendingIntent
PendingIntent pendingIntent = PendingIntent.getActivity(context, requestCode , intent, PendingIntent.FLAG_UPDATE_CURRENT);
+9

All Articles