【发布时间】:2021-02-17 14:23:36
【问题描述】:
我在我的应用中使用单一活动架构。现在我一直在处理通知。我收到来自 firebase 的通知,当应用程序在后台运行时,谷歌播放服务可以很好地处理此类通知。当它被点击时,它将应用程序从后台带到前台(它不会重新创建活动/应用程序)。
当应用程序处于前台时,我需要对收到的通知具有相同的行为。因此,我在我的 firebase 服务中覆盖 onMessageReceived() 并在此处创建新通知。我尝试了许多 Intent's Flags 变体传递给通知和 launchMode 清单,但它总是导致活动重新创建(活动具有不同的哈希码,它是 onCreate() 它被调用)之后点击onMessageReceived() 创建的通知。
代码如下:
@Override
public void onMessageReceived(@NonNull RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Logger.d("Msg received " + remoteMessage.getNotification().getTitle());
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this, FCM_CHANNEL_ID)
.setContentTitle(remoteMessage.getNotification().getTitle())
.setContentText(remoteMessage.getNotification().getBody())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true)
.setStyle(new NotificationCompat.BigTextStyle().bigText(remoteMessage.getNotification().getBody()))
.build();
NotificationManagerCompat manager = NotificationManagerCompat.from(getApplicationContext());
manager.notify(FCM_NOTIFICATION_ID, notification);
}
manifest: android:launchMode="singleTask"
知道要改变什么来防止活动重新进行吗? (我在 android 10 上测试,MainActivity 扩展了 AppCompatActivity) 谢谢。
【问题讨论】:
标签: android android-activity android-notifications