我在我的项目中实现了FCM。推送通知按预期工作,当接收到通知时,会调用onMessageReceived。当应用程序处于前台时此为真。
然而,当应用程序在后台运行时,如果有通知到达,则系统托盘始终显示重复的通知(例如,当接收到通知A时,系统托盘显示2个通知A)。
如何解决这个问题?
编辑:添加代码
我扩展了FirebaseMessagingService类,并在onMessageReceived方法中使用了NotificationManager。
这是项目中仅有的部分。
另外,我尝试在此方法上添加日志。当应用程序在前台运行时会调用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());
}