【问题标题】:Firebase FCM send notification OnMessageReceived PendingIntent show current activityFirebase FCM 发送通知 OnMessageReceived PendingIntent 显示当前活动
【发布时间】:2023-03-04 00:14:01
【问题描述】:

我有一个包含多个活动的应用程序。我正在实施 Firecbase FCM,除了处理用户在收到通知图标时单击通知图标时要转到哪个活动之外,它一切都很好。

由于我不确定 FirebaseMessagingService 是如何/何时实例化的,因此我无法对其进行设置以访问我的任何对象。我唯一能做的就是将当前的 Activity 在 App 中存储为

public static Activity CurrentActivity { get; set; }

然后我在每个活动的 OnCreate() 中设置上述内容,然后在 FirebaseMessagingService .OnMessageReceived() 中设置我的待处理意图,如下所示:

        Intent intent = new Intent(this, App.CurrentActivity.GetType());

        intent.AddFlags(ActivityFlags.SingleTop);           

        var pendingIntent = PendingIntent.GetActivity(this, App.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);

        var notificationBuilder = new NotificationCompat.Builder(this, App.CHANNEL_ID)
                                  .SetSmallIcon(Resource.Drawable.ic_notification)
                                  .SetContentTitle("FCM Message")
                                  .SetContentText("test")
                                  .SetAutoCancel(true)    //dismisses the notification on click
                                  .SetContentIntent(pendingIntent);

        var notificationManager = NotificationManagerCompat.From(this);
        notificationManager.Notify(App.NOTIFICATION_ID, notificationBuilder.Build());

到目前为止,这是有效的,因此当用户单击通知时,它会转到正确的活动。

问题是当用户在活动 A 但没有点击它并移动到活动 B 然后点击通知时,如果收到通知。我的 Pending Intent 将是 Activity A。但是在显示 Notification 之后,将显示 Activity A。

我在想是否可以在 OnMessageReceived() 中检测应用程序是在前台还是后台,然后如果在前台我可以做并打算显示消息的警报对话框,如果在后台,那么我的原始代码可以正常工作。

有没有人知道这是否可行以及如何实现?

【问题讨论】:

  • 定义一个静态变量并在 onResumt() 和 onPause() 中改变它的值来检测它。
  • 更新:我已经设法解决了这个问题。对于在我的 FirebaseMessagingService.OnMessageReceived() 中遇到类似问题的任何其他人,我为名为 NotificationActivity 的标准活动创建了 PendingIntent。我从 message 参数中提取了发送的正文和标题,并将其传递给 NotificationActivity。

标签: android firebase-notifications


【解决方案1】:

我已经设法解决了这个问题,所以我想我会为遇到类似问题的其他人发布更新。

在我的 FirebaseMessagingService.OnMessageReceived() 中,我为一个名为 NotificationActivity 的标准活动创建了 PendingIntent。

public override void OnMessageReceived(RemoteMessage message)

message 我提取了正文和标题并传递给 NotificationActivity

NotificationActivity.OnCreate() 然后将只显示一个 AlertDialog 并单击 OK 我使用 this.Finish() 关闭了活动

当用户在应用程序中收到通知时,这非常有效。用户可以单击通知,它将显示 AlertDialog。关闭时,它只会恢复当前的活动。

【讨论】:

  • 只是一个关于应用程序何时处于后台或被杀死的问题。在这种情况下,pendingIntent 有什么帮助?
  • 我没有方便测试的代码,但来自内存,但它在顶部显示一个通知图标,当您向下拖动并选择它时,它会将应用程序带到前台(如果背景)。我很确定如果它被杀死它也会启动应用程序(但我会在重新工作时测试)
猜你喜欢
  • 1970-01-01
  • 2022-08-22
  • 2021-09-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-29
相关资源
最近更新 更多