【问题标题】:Notification show twice on flutter通知在颤动上显示两次
【发布时间】:2022-06-28 22:19:39
【问题描述】:

我被困住了。我在后台的通知显示了两次。但在前台只有一个通知。这是我的代码

Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  await Firebase.initializeApp();
  if(
      !AwesomeStringUtils.isNullOrEmpty(message.notification?.title, considerWhiteSpaceAsEmpty: true) ||
      !AwesomeStringUtils.isNullOrEmpty(message.notification?.body, considerWhiteSpaceAsEmpty: true)
    ){
      // print('message also contained a notification: ${message.notification.body}');
      
      String imageUrl;
      imageUrl ??= message.notification.android?.imageUrl;
      imageUrl ??= message.notification.apple?.imageUrl;
      print(imageUrl);
      if(imageUrl == null){
        var id = Random().nextInt(2147483647);
        await AwesomeNotifications().createNotification(
          content: NotificationContent(
            id: id,
            title: message.notification.title,
            body: message.notification.body,
            color: Colors.orange,
            customSound: 'resource://raw/alert',
            notificationLayout: NotificationLayout.BigText,
            channelKey: 'basic_channel_background',
            payload: {'data':message.data['payload']}
          ),
          actionButtons: [
            NotificationActionButton(
              label: 'Lihat Selengkapnya',
              enabled: true,
              buttonType: ActionButtonType.Default,
              key: 'background',
            )
          ]
        );
      }else{
        await AwesomeNotifications().createNotification(
          content: NotificationContent(
            id: Random().nextInt(2147483647),
            title: message.notification.title,
            body: message.notification.body,
            bigPicture: imageUrl,
            color: Colors.orange,
            customSound: 'resource://raw/alert',
            notificationLayout: NotificationLayout.BigPicture,
            channelKey: 'basic_channel_background',
            payload: {'data':message.data['payload']}
          ),
          actionButtons: [
            NotificationActionButton(
              label: 'Lihat Selengkapnya',
              enabled: true,
              buttonType: ActionButtonType.Default,
              key: 'background',
            )
          ]
        );
      }
    }
}
// End Background Message

这是我的前台代码

// Foreground Apps
Future<void> main() async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  if (!kIsWeb) {
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
    await AwesomeNotifications().initialize(
    'resource://mipmap/launcher_icon',
    [
      NotificationChannel(
          channelGroupKey: 'basic_tests',
          channelKey: 'basic_channel',
          channelName: 'My Cahaya Notification',
          channelDescription: 'Notification channel for basic tests',
          icon: 'resource://mipmap/launcher_icon',
          importance: NotificationImportance.High,
          playSound: true,
          soundSource: 'resource://raw/alert'
      ),
       NotificationChannel(
          channelGroupKey: 'basic_background',
          channelKey: 'basic_channel_background',
          channelName: 'My Cahaya Notification Background',
          channelDescription: 'Notification channel for basic tests',
          icon: 'resource://mipmap/launcher_icon',
          importance: NotificationImportance.High,
          playSound: true,
          soundSource: 'resource://raw/alert'
      ),
    ], debug: true);
    AwesomeNotifications().actionStream.listen((event) async{
      print('event received!');
      var data = event.toMap();
      if(data['buttonKeyPressed'] == "background"){
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString("Navigate", data['payload']['data']);
      }else{
        _navigateToItemForeground(data['payload']['data']);  
      }
      // do something based on event...
      // AwesomeNotifications().actionSink.close();
    });
  } 
  
   FirebaseMessaging.onMessage.listen((RemoteMessage message) async{
      RemoteNotification notification = message.notification;
      AndroidNotification android = message.notification?.android;
      if (notification != null && android != null && !kIsWeb) {
        if(!AwesomeStringUtils.isNullOrEmpty(message.notification?.title, considerWhiteSpaceAsEmpty: true) ||
        !AwesomeStringUtils.isNullOrEmpty(message.notification?.body, considerWhiteSpaceAsEmpty: true)){
        print("something");

        String imageUrl;
        imageUrl ??= notification.android?.imageUrl;
        imageUrl ??= notification.apple?.imageUrl;
        
        if(imageUrl == null){
          await AwesomeNotifications().createNotification(
            content: NotificationContent(
              id: Random().nextInt(2147483647),
              title: notification.title,
              body: notification.body,
              color: Colors.orange,
              customSound: 'resource://raw/alert',
              notificationLayout: NotificationLayout.BigText,
              channelKey: 'basic_channel',
              payload: {'data':message.data['payload']}
            ),
            actionButtons: [
              NotificationActionButton(
                label: 'Lihat Selengkapnya',
                enabled: true,
                buttonType: ActionButtonType.Default,
                key: 'test',
              )
            ]
          );
        }else{
          await AwesomeNotifications().createNotification(
            content: NotificationContent(
              id: Random().nextInt(2147483647),
              title: notification.title,
              body: notification.body,
              bigPicture: imageUrl,
              color: Colors.orange,
              customSound: 'resource://raw/alert',
              notificationLayout: NotificationLayout.BigPicture,
              channelKey: 'basic_channel',
              payload: {'data':message.data['payload']}
            ),
            actionButtons: [
              NotificationActionButton(
                label: 'Lihat Selengkapnya',
                enabled: true,
                buttonType: ActionButtonType.Default,
                key: 'test',
              )
            ]
          );
        }
      }
    }
  });
  runApp(MyApp());
}
// End Foreground Apps

这是我的截图 screenshot

我尝试更改了很棒的通知,但结果是一样的。你能帮我解决这个问题吗?我希望你能帮助我。非常感谢

【问题讨论】:

    标签: android firebase flutter


    【解决方案1】:

    FCM 负载

    
    {
        "to":"_some_fcm_token_",
        //remove this
        "notification": {
            "title": "this is title",
            "body": "this is subtitle"
        },
        "type": "post_like",
        "data": {
            "model":{"id":"dsaflkdskfklgdkgjdksakdk"},
            "body": "this is subtitle",
            "title": "this is title",
            "click_action": "FLUTTER_NOTIFICATION_CLICK"
        },
        "priority": "normal"
    }
    
    

    第一个是手动创建的(本地),另一个是由 Firebase 自动创建的。

    向您的设备发送消息时,请确保它是notification 而不是datadocumentation 提到,如果您发送数据,它可能会作为推送通知被忽略。仅用于将数据包发送到应用程序。

    【讨论】:

    • 0 我已发送通知而非数据。但是我的手机在我的应用程序未打开时收到两个通知。当我的应用程序打开时,我尝试向我的手机发送通知,我的手机会收到一条通知
    • 我在您的代码中看到了数据。有效载荷:{'data':message.data['payload']}
    • 为什么要使用我的有效载荷?我可以删除它吗?
    • 是的,当您使用message.data时,firebase 会自动发送推送通知。
    • 我已经删除了,结果是一样的。当我的应用程序关闭时,我的通知会显示两次。我现在该怎么办?
    【解决方案2】:

    如果您的通知是在应用处于后台时发送的,Firebase 自动发送 Push-Notification,无需在 App 中手动调用 show Notification。

    我解决了这样的问题:

    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      if (message.notification != null) {
        //No need for showing Notification manually. 
        //For BackgroundMessages: Firebase automatically sends a Notification.
        //If you call the flutterLocalNotificationsPlugin.show()-Methode for
        //example the Notification will be displayed twice.
      }
      return;
    }
    

    【讨论】:

      【解决方案3】:

      已解决)

      **{
          "to":"_some_fcm_token_",
          //remove this
          //"notification": {
           //   "title": "this is title",
            //  "body": "this is subtitle"
          },
          "type": "post_like",
          "data": {
              "model":{"id":"dsaflkdskfklgdkgjdksakdk"},
              "body": "this is subtitle",
              "title": "this is title",
              "click_action": "FLUTTER_NOTIFICATION_CLICK"
          },
          "priority": "normal"
      }**
      

      【讨论】:

        猜你喜欢
        • 2022-11-13
        • 2022-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多