You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按Firebase文档创建Android高优先级通知通道以显示前台FCM通知?

Android前台FCM通知显示的解决方案

核心结论:仅创建高优先级通知通道不够,还需要在代码中手动处理前台消息的回调逻辑;不一定非要用flutter_local_notifications,但这个包能大幅简化开发流程。

为什么控制台设置优先级前台不生效?

FCM在Android上的行为分两种场景:

  • 应用后台/杀死状态:消息由系统级FCM服务处理,会自动根据通道优先级弹出通知,所以你之前设置高优先级能生效。
  • 应用前台状态:消息会直接传递到Flutter应用的onMessage回调,系统不会自动触发通知——不管通知通道优先级多高都没用,必须由你自己在回调里手动触发通知显示。

无需第三方包的实现方式

  1. 先创建高优先级通知通道(这是前提,确保通知能以高优先级弹出)
    在Android原生代码中(比如MainActivity.kt)创建通道:

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 创建高优先级通知通道
        val channelId = "high_priority_fcm_channel"
        val channelName = "High Priority FCM Notifications"
        val channel = NotificationChannel(
            channelId,
            channelName,
            NotificationManager.IMPORTANCE_HIGH
        ).apply {
            description = "用于前台显示的FCM通知通道"
            enableVibration(true)
            setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION), AudioAttributes.DEFAULT_NOTIFICATION)
        }
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.createNotificationChannel(channel)
    }
    
  2. 在Flutter中处理前台消息回调
    通过FirebaseMessaging.onMessage.listen监听前台消息,然后调用原生方法手动构建并显示通知。这一步需要写Flutter与Android的桥接代码,比如通过MethodChannel调用原生的NotificationManager来发送通知。

用flutter_local_notifications的优势

官方文档没直接提及这个包,但它是社区公认的简化方案:

  • 封装了Android和iOS的通知API,无需写原生桥接代码,直接在Flutter层面构建通知。
  • 可以轻松指定使用你创建的高优先级通道,一行代码就能在onMessage回调中弹出通知:
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;
      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
          notification.hashCode,
          notification.title,
          notification.body,
          NotificationDetails(
            android: AndroidNotificationDetails(
              "high_priority_fcm_channel", // 对应你创建的通道ID
              "High Priority FCM Notifications",
              importance: Importance.high,
              priority: Priority.high,
              icon: android.smallIcon,
            ),
          ),
        );
      }
    });
    

总结

  • 高优先级通知通道是必要前提,但不能单独解决前台显示问题。
  • 必须处理前台消息的onMessage回调,手动触发通知显示。
  • 不用第三方包也能实现,但需要写原生代码;用flutter_local_notifications更高效,是行业常规做法。

内容的提问来源于stack exchange,提问作者shingo.nakanishi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 09:07:15