【问题标题】:Notification in single Activity architecture单 Activity 架构中的通知
【发布时间】: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


    【解决方案1】:

    终于搞定了。所有的魔法都是通过将这两行添加到我的代码中来完成的。

    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    

    Original answer

    【讨论】:

      【解决方案2】:

      你试过了吗?

      intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      

      【讨论】:

      • 是的,我做到了,没有区别。 MainActivity 已重新创建。
      【解决方案3】:

      使用 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK 标志。

      这将作为堆栈的根启动活动。

      【讨论】:

      • 我已经尝试过了,但活动总是被重新创建
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      • 1970-01-01
      • 2022-01-09
      • 2017-04-04
      相关资源
      最近更新 更多