通知在 flutter 上显示两次

2024-01-27

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

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

这是我的屏幕截图截屏 https://i.stack.imgur.com/FLwYh.png

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


如果您的通知是在应用程序处于后台时发送的,Firebase 自动发送推送通知,因此您无需在应用程序中手动调用显示通知。

我这样解决了这个问题:

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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通知在 flutter 上显示两次 的相关文章

  • React-Native 中的导航抽屉

    我是反应原生的新手 不介意我问一个基本问题 我想知道 实现抽屉式导航的分步过程是什么 推荐链接这个链接 https github com react native community react native side menu usage
  • 使用 HashMap 映射 String 和 int

    我有一个显示国家 地区名称的列表视图 我已将名称作为字符串数组存储在 strings xml 中 称为国家 地区名称 在填充 ListView 时 我使用从 strings xml 读取的 ArrayAdapter String count
  • 为什么Android room不建议使用allowMainThreadQueries()?

    我正在创建一个小型应用程序 仅在数据库中保存一些计数器 如果不存在 请插入一个 如果是的话 增加更新 该应用程序没有任何用户界面 它是一个保存和读取数据 少量表 少量记录 的插件 我可以用吗允许主线程查询 在这种情况下 每次我读到一些关于这
  • 从 Android 函数更新 Textview

    有人可以告诉我如何从函数更新 Android Textview 控件吗 我在互联网上进行了深入搜索 看到很多人都问同样的问题 我测试了线程但无法工作 有人有一个简单的工作示例吗 例如 调用一个函数 在循环中运行多次 并且该函数在 TextV
  • Google play APK 上传错误重复权限声明

    我尝试上传新的 apk 使用我自己的发布密钥存储签名 并在 google play 开发者控制台中收到以下错误 重复的许可声明 android permission ACCESS COARSE LOCATION 与不同 maxSdkVers
  • Google Play 服务,登录成功,但创建房间时出错

    我正在尝试 google play 服务示例 特别是 ButtonClicker2000 从 logcat 登录过程也正常 但我有另一个错误 06 01 22 43 15 478 D ButtonClicker2000 1565 Sign
  • 如何以编程方式关闭画中画

    我在使用画中画模式时遇到了这个问题 当从 PIP 本身以外的其他位置再次打开 Activity 时 我想关闭 PIP 画中画 不是来自关闭按钮 我想要与 youtube 相同的场景 即当用户单击 PIP 画中画 时 它会打开相同的活动 但是
  • Android TextView 中的等宽表格数字

    我有一个自定义字体 默认情况下具有可变宽度数字字形 并且我想在 Android 中使用该字体的等宽表格数字功能TextView使数字垂直对齐 也就是说 改变如下 像这样的事情 要选择字体的表格数字功能 请使用TextView s fontF
  • 标签栏随键盘一起上升

    这个问题之前已经发过 但是没有答案 Problem TabBar gt 2 个选项卡 选项卡一有一个Scrollview and an EddiText 标签二 其他 贴带时EditText 软键盘上升 TabBar与它一起 一个丑陋的解决
  • 无法读取第 0 行,第 -1 列

    我正在尝试复制使用 SQLite 管理器创建的数据库 我在其中执行了以下操作 CREATE TABLE android metadata locale TEXT DEFAULT en US and INSERT INTO android m
  • 为什么此 Firebase 可调用函数不返回值?

    我有一个应返回值的可调用函数 但唯一返回的是 null 以下是该功能的当前版本 我也尝试过回报第一个承诺 原来的once调用 最后在另一个then返回 GUID 在这种情况下它实际上返回了数据 但它立即返回并且 GUID 为空 我怎样才能实
  • android gradle插件-离线安装

    我必须在离线电脑上安装 android gradle 插件 通过谷歌搜索 我了解到我可以通过本地 Maven 存储库来做到这一点 但从不成功的尝试和所有关于这个问题的质量保证中我知道这并不简单 我从来没有和maven一起工作过 有经验的人可
  • 如何解决Android错误类型3?

    下面是我在项目中使用的清单格式 但是每当我尝试运行模拟器时 我都会收到下面提到的错误 请给我一个解决该错误的准确解决方案 工具信息 Android studio Nexus S API 22 android 5 1 1 我的清单文件格式
  • 在异步请求中使用超时回调

    我之前问过这个问题 但我将用提出的解决方案来完成这个问题 并提出另一个问题 我正在使用这个类来进行异步网络请求 http msdn microsoft com en us library system net webrequest aspx
  • 运行 flutter doctor 吐出错误:标准错误:致命:坏对象 HEAD

    我已经从官方网站安装了 Flutter 和 Android Studio 我是 Git GitHub 移动开发和 Android 开发的新手 我试图在命令提示符 Windows 10 中运行 flutter doctor 命令 但是 它会以
  • React Native v0.71.8 React-native-vector-icons 你看不到的图标

    我在用react native版本v0 71 8 我安装了react native vector icons库 但图标未显示 似乎链接在最新版本的 React Native 中不再起作用 所以我按照说明进行操作 但它不再编译 出现以下错误
  • Android 导航 DeepLinks - 如何区分使用导航操作进行导航与深层链接

    我有导航操作和深层链接 根据您导航的位置 将您带到某个片段 我想确定是使用了深层链接还是仅使用了导航操作 这正是KEY DEEP LINK INTENT https developer android com reference andro
  • 地理围栏不可用以及如何处理

    我正在 Android 上使用地理围栏 它在大多数手机上都工作正常 但在其中一些上 它不起作用 在我的错误日志中显示 地理围栏不可用 某些用户没有为 Google Play 服务启用位置跟踪 我认为这就是地理围栏在他们的手机上不起作用的原因
  • 获取接收者的设备令牌以在 Firebase 中发送通知

    所以我正在学习如何使用 firebase 发送设备到设备的通知 我看到了这个answer https stackoverflow com a 42548586 5237289发送通知 看起来很简单 现在 我知道要获取发件人的令牌 它应该如下
  • Android 可扩展列表视图随机播放子项

    你好 我正在使用 Android Expandable listview 并用不同的视图在其中膨胀子视图 我遇到的问题是 当我展开视图然后打开另一个父视图时 布局中的子视图会变得混乱并在代码中膨胀错误的布局 这是我的两个项目的示例代码 这是

随机推荐