首页 > 解决方案 > 点击通知仅打开最后一个(最后收到)

问题描述

我需要有关 Android 通知方面的帮助。我的服务器向新通知发送具有唯一 ID 的请求(到 firebase 服务器)。如果我的设备会收到它,则会创建并通知新通知。如果我将发送下一个具有其他唯一 ID 的请求,则会创建新通知。状态栏上有两个通知。每个通知在 Intent 中都有一些数据,我想在 Activity 中显示它。但是在单击第一个或第二个或最后一个(如果设备收到 2 个或更多通知)后,它会导致从最后收到的(通知堆栈的顶部)启动 Activity(带有 Intent)。我认为这个问题存在于 Intent 或 PendingIntent 上的某些标志中。

 @Override
public void onMessageReceived(RemoteMessage respose ) {

    JSONObject response_intent=null;

    try {
        response_intent= new JSONObject( respose.getData().get("intent"));
    } catch (JSONException e) {
        e.printStackTrace();
    }

    int unique_id=Integer.valueOf(respose.getData().get("id_original"));
    /*After notification click to open Activity ... */

    Intent intent = new Intent("eu.energochemica.cat_notifications.DETAIL_SCREEN");
    /*... with  data from firebase via Intent */

    intent.putExtra("fromNotification", true);
    intent.putExtra("intentFromNotification", respose.getData().get("intent"));
    intent.putExtra("id_original",unique_id);
    intent.putExtra("header",respose.getData().get("header"));
    intent.putExtra("text",respose.getData().get("text"));

    /*HERE? What FLAG to use?*        Intent.FLAG_ACTIVITY_NEW_TASK     */      
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    /*OR HERE? What FLAG to use?*/
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); 

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, Config.NOT_CHANNEL_ID)
            .setSmallIcon(this.getResources().getIdentifier("cat_logo_white", "drawable", this.getPackageName()))
            .setContentTitle(respose.getData().get("header"))
            .setContentText(respose.getData().get("text"))
            .setAutoCancel(false)
            .setChannelId(Config.NOT_CHANNEL_ID)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" +this.getPackageName()+"/"+R.raw.notif))
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =   (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(unique_id, notificationBuilder.build());

}

我需要(如果我连续收到四个通知: 1, 2, 3, 4 ,其中 4 是最后一个(最新))以正确的 Intent 打开 Activity。 (单击通知 1(最旧的)将从此通知 1 中打开带有 Intent 的 Activity,并且不会从通知 4 中打开 Intent)

我不知道如何以及如何处理代码,FLAG。有谁能够帮我?

标签: android-intentandroid-activitygoogle-cloud-messagingandroid-notificationsandroid-pendingintent

解决方案


哦,我的错...我发现了问题的地方...阅读官方描述后PendingIntent.class,我尝试将 unique_id 传递给第二个参数 [ int requestCode ]

PendingIntent.getActivity(this, u_id,  intent, ...

反而

PendingIntent.getActivity(this, 0, intent, ...

其中常量 0 表示“重写”相同的 PendingIntent(在我看来)=> 0 是 PendingIntent 的 ID。


推荐阅读