每次登录都会收到相同的通知

问题描述 投票:0回答:1

我正在创建一个聊天应用程序,每当我发送消息时,我都会在第二台设备上收到通知。每次登录时,我都会收到相同的通知。

这是我的 FirebaseNotificationService 类

@SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class FirebaseNotificationService extends FirebaseMessagingService {
    public static final String CHANNEL_ID_1 = "channel_1";
    public static final String CHANNEL_ID_2 = "channel_2";
    @SuppressLint("NewApi")
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        String title = Objects.requireNonNull(remoteMessage.getNotification()).getTitle();
        String text = Objects.requireNonNull(remoteMessage.getNotification()).getBody();
        assert title != null;
        if (title.contains("chat")) {
            PendingIntent contentIntent = PendingIntent.getActivity(
                    this,
                    255,
                    new Intent(this, SplashActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.cancel(contentIntent);
            NotificationChannel channel_chat = new NotificationChannel(
                    CHANNEL_ID_2,
                    "Message Notification",
                    NotificationManager.IMPORTANCE_HIGH);
            getSystemService(NotificationManager.class).createNotificationChannel(channel_chat);
            Notification.Builder notification_chat = new Notification.Builder(this, CHANNEL_ID_2)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setSmallIcon(R.drawable.logo)
                    .setContentIntent(contentIntent)
                    .setPriority(Notification.PRIORITY_DEFAULT)
                    .setAutoCancel(true);
            NotificationManager manager = getSystemService(NotificationManager.class);
            NotificationManagerCompat.from(this).notify(255, notification_chat.build());
            if (manager != null) {
                manager.notify(255, notification_chat.build());
            }
        } else {
            PendingIntent contentIntent = PendingIntent.getActivity(
                    this,
                    255,
                    new Intent(this, SplashActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
            alarmManager.cancel(contentIntent);
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID_1,
                    "Message Notification",
                    NotificationManager.IMPORTANCE_HIGH);
            getSystemService(NotificationManager.class).createNotificationChannel(channel);
            Notification.Builder notification = new Notification.Builder(this, CHANNEL_ID_1)
                    .setContentTitle(title)
                    .setContentText(text)
                    .setSmallIcon(R.drawable.logo)
                    .setContentIntent(contentIntent)
                    .setPriority(Notification.PRIORITY_DEFAULT)
                    .setAutoCancel(true);
            NotificationManager manager = getSystemService(NotificationManager.class);
            NotificationManagerCompat.from(this).notify(255, notification.build());
            if (manager != null) {
                manager.notify(255, notification.build());
            }
        }
        super.onMessageReceived(remoteMessage);
    }
    private void broadcastNewNotification() {
        Intent intent = new Intent(NEW_NOTI);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
    public static final String NEW_NOTI = "new_notification";
}

public class FCMSender {
    Context context;
    private final String postUrl = "https://fcm.googleapis.com/fcm/send";
    private final String fcmServerKey = "fcmServerKey";
    public FCMSender(Context context) {
        this.context = context;
    }
    public void pushNotification(String token, String title, String body) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        JSONObject mainObj = new JSONObject();
        try {
            mainObj.put("to", token);
            JSONObject notyObject = new JSONObject();
            notyObject.put("title", title);
            notyObject.put("body", body);
            notyObject.put("icon", R.drawable.logo); // enter icon that exists in drawable only
            mainObj.put("notification", notyObject);
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, postUrl, mainObj, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> header = new HashMap<>();
                    header.put("Content-Type", "application/json");
                    header.put("Authorization", "key=" + fcmServerKey);
                    return header;
                }
            };
            requestQueue.add(request);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

如何让通知只出现一次?

编辑:我添加 FCMSender 类发送部分

java android push-notification firebase-cloud-messaging
1个回答
0
投票

1.尝试在您的 Volley 请求中使用它 // 重试策略

 req.setRetryPolicy(new DefaultRetryPolicy(
                5000, // 5 seconds timeout
                4,    //  retries
                2.0f  // Backoff multiplier
        ));
        req.setTag(TAG);

2.notificationId 对于每条新消息,您确保每个通知都有一个唯一的标识符。

@SuppressLint("MissingFirebaseInstanceTokenRefresh")
public class FirebaseNotificationService extends FirebaseMessagingService {
    public static final String CHANNEL_ID_1 = "channel_1";
    public static final String CHANNEL_ID_2 = "channel_2";
   
    private static int notificationId = 0;

    @SuppressLint("NewApi")
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
      
        // Increment the notificationId for each new message or use date & time as id
        notificationId++;

        // Use the unique notificationId for each notification
        NotificationManagerCompat.from(this).notify(notificationId, notification_chat.build());
        if (manager != null) {
            manager.notify(notificationId, notification_chat.build());
        }

  
    }

  
}
© www.soinside.com 2019 - 2024. All rights reserved.