后台通知 OnClick 使用 FCM Flutter 应用程序打开一个空活动

发布于 2025-01-16 01:56:19 字数 2640 浏览 3 评论 0原文

我遵循了 flutter 文档中关于如何使用新的 flutter android 嵌入 v2 实现 firebase_messaging 的每一步,

我在每个应用程序状态(前台/后台/终止或分离)下接收通知都没有问题。单击通知在除终止之外的其他状态下效果良好。

在终止状态,当我尝试单击应用程序分离时收到的通知时,它会打开应用程序,但我在 getInitialMessage 函数中没有收到任何数据我应该(根据文档)。另外,当我尝试按后退按钮离开应用程序时,应用程序在其下方显示了一个额外的空活动,我不确定为什么会发生这种情况。我想摆脱它。

仅当在终止状态下收到通知时才会出现这些问题。

即使在终止状态下,onBackgroundMessage 侦听器也能完美工作。

main.dart :

Future<void> _backgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Message from background : " + message.notification.body);
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  //init notification service
  await NotificationService().initNotification();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_backgroundHandler);

home_page_screen.dart : setupInteractedMessage() 在 initState() 中调用

Future<void> setupInteractedMessage() async {
    //Terminated State
    //Comes in from terminated app's notification
    FirebaseMessaging.instance.getInitialMessage().then((value) => {
          if (value != null)
            {print("ContentAvailable : " + value.contentAvailable.toString())}
        });

    //Foreground state
    FirebaseMessaging.onMessage.listen((event) {
      String title = event.notification.title;
      String body = event.notification.body;
      int tag = int.parse(event.data["tag"]);
      //Dont show notification if inside conversation with the sender
      if (!Provider.of<ConversationBloc>(context, listen: false)
          .disableNotification(tag)) {
        NotificationService()
            .showNotification(tag, title, body, json.encode(event.data));
      } else {
        soundHandler.playOnNewMessageSound();
      }

      print("Received in foreground");
    });

    //Opened from background notification trigger and handler
    //It does not work if the app is detached only works in paused state
    FirebaseMessaging.onMessageOpenedApp.listen((event) {
      NotificationService().selectNotification(json.encode(event.data));
      print("Received in background while the app is paused and not detached");
    });
  }

视频: https://drive.google.com/file/d/1-De9Buv6ToLB13hIat7i9uZsQOSS2XJO/view?usp=drivesdk

我的参考: https://firebase.flutter.dev/docs/messaging/usage

I followed every step in the flutter documentation on how to implement firebase_messaging with the new flutter android embedding v2

I have no problem with receiving the notification in every app state (Foreground/Background/Terminated or Detached). Clicking on the notification works perfectly on other state except terminated.

In terminated state, when I try to click on the notification that is received while the app is detached, it opens up the application but I do not receive any data in getInitialMessage function which I should (according to the doc). Also, when I try to leave the app by pressing the back button, somehow the app shows an extra empty activity underneath it and I'm not sure why this happen. I want to get rid of it.

These problems only occurs if the notification received in terminated state.

The onBackgroundMessage listener works perfectly even in terminated state.

main.dart :

Future<void> _backgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Message from background : " + message.notification.body);
}

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  //init notification service
  await NotificationService().initNotification();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_backgroundHandler);

home_page_screen.dart :
setupInteractedMessage() is called in initState()

Future<void> setupInteractedMessage() async {
    //Terminated State
    //Comes in from terminated app's notification
    FirebaseMessaging.instance.getInitialMessage().then((value) => {
          if (value != null)
            {print("ContentAvailable : " + value.contentAvailable.toString())}
        });

    //Foreground state
    FirebaseMessaging.onMessage.listen((event) {
      String title = event.notification.title;
      String body = event.notification.body;
      int tag = int.parse(event.data["tag"]);
      //Dont show notification if inside conversation with the sender
      if (!Provider.of<ConversationBloc>(context, listen: false)
          .disableNotification(tag)) {
        NotificationService()
            .showNotification(tag, title, body, json.encode(event.data));
      } else {
        soundHandler.playOnNewMessageSound();
      }

      print("Received in foreground");
    });

    //Opened from background notification trigger and handler
    //It does not work if the app is detached only works in paused state
    FirebaseMessaging.onMessageOpenedApp.listen((event) {
      NotificationService().selectNotification(json.encode(event.data));
      print("Received in background while the app is paused and not detached");
    });
  }

Video :
https://drive.google.com/file/d/1-De9Buv6ToLB13hIat7i9uZsQOSS2XJO/view?usp=drivesdk

My reference :
https://firebase.flutter.dev/docs/messaging/usage

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

栀子花开つ 2025-01-23 01:56:19

尝试将此意图标记添加到 AndroidManifest.xml 内的活动标记中。

<activity>

....
 
<intent-filter> // <= add this
    <action android:name="FLUTTER_NOTIFICATION_CLICK" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

....

并且不要忘记在发送 FCM 时将字段“click_action”添加到您的负载中。例如:'click_action':'FLUTTER_NOTIFICATION_CLICK'

try adding this intent tag to your activity tag inside AndroidManifest.xml.

<activity>

....
 
<intent-filter> // <= add this
    <action android:name="FLUTTER_NOTIFICATION_CLICK" />
    <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

....

and don't forget to add field 'click_action' to your payload when sending FCM. eg : 'click_action' : 'FLUTTER_NOTIFICATION_CLICK'.

入画浅相思 2025-01-23 01:56:19

onMessageOpenedApp 状态的文档

A Stream event will be sent if the app has opened from a background state (not terminated).
If your app is opened via a notification whilst the app is terminated,
see [getInitialMessage].

因此您必须使用 getInitialMessage 来尝试添加一些延迟,

Future.delayed(Duration(seconds: 2),(){
    // handle app opened from notification
    RemoteMessage? remoteMessage = await FirebaseMessaging.instance.getInitialMessage();
    // add your custom code here
});

The docs for onMessageOpenedApp state

A Stream event will be sent if the app has opened from a background state (not terminated).
If your app is opened via a notification whilst the app is terminated,
see [getInitialMessage].

So you have to go with getInitialMessage to try to add some delay,

Future.delayed(Duration(seconds: 2),(){
    // handle app opened from notification
    RemoteMessage? remoteMessage = await FirebaseMessaging.instance.getInitialMessage();
    // add your custom code here
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文