我在项目中实施了FCM。推送通知按预期方式工作,在收到通知时调用onMessageReceived。当应用程序位于前台时,这是正确的。
但是,当应用程序在后台运行时,系统托盘始终在到达时显示重复的通知(例如,收到通知A时,系统托盘显示2通知A)。
如何解决这个问题?
编辑:添加代码
我扩展了FirebaseMessagingService类并将其包含在onMessageReceived方法中
这是项目中我使用NotificationManager的唯一部分。
另外,我尝试在此方法上添加日志。当应用程序处于前台时,将调用onMessageReceived。应用程序在后台时不会被调用
@Override
public void onMessageReceived(RemoteMessage remoteMessage)
{
RemoteMessage.Notification notification = remoteMessage.getNotification();
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
String title = notification.getTitle();
String message = notification.getBody();
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
Run Code Online (Sandbox Code Playgroud) android android-notifications firebase firebase-cloud-messaging