通知将被相互覆盖

时间:2014-12-12 11:27:02

标签: android android-intent android-notifications android-notification-bar

我发送不同的通知。但是当你点击其中任何一个时,我都会得到已经发送到最后一个通知的数据。怎么解决?我需要注意每个商店他们的数据,并且新的通知不会替换它们。我使用标志PendingIntent.FLAG_UPDATE_CURRENT但我也使用左边的所有标志提供。

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);
    }

1 个答案:

答案 0 :(得分:10)

诀窍是为每个不同的通知在PendingIntent上添加不同的requestCode

文档是:

public static PendingIntent getActivity(Context context, int requestCode ,Intent intent,int flags)

系统使用它来比较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);