I’m creating a chat app where I receive notifications on my second device whenever I send a message. Each time I log in, I consistently receive the same notification.
this is my FirebaseNotificationService class
@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";
}
How can I make the notifications come only once?