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

Flutter应用锁屏5分钟后FCM通知无法接收问题求助

问题:锁屏一段时间后无法接收FCM通知

问题详情

应用终止状态下可正常接收FCM通知;锁屏后前5分钟能收到通知,之后无法接收;解锁设备后通知恢复正常。已获取后台运行、通知、锁屏显示通知等所有必要权限。

现有代码

通知发送代码

sendVoicePushNotification({required userToken,required String currentName,required String voiceUrl}) async {
try {
  print("user token is: $userToken");
  final body = {
    "to": userToken,
    "notification": {
      "title": currentName,
      "body": 'New voice message',
      "android_channel_id": "voice",
    },
    'android': {
      'priority': 'high',
    },
    'data':{
      'type':'voice',
      'id':'1234',
      'voiceUrl': voiceUrl
    }
  };
  var res = await http.post(
      Uri.parse('https://fcm.googleapis.com/fcm/send'),
      headers: {
        'Content-Type': 'application/json;char=UTF-8',
        'Authorization': 'key=' },
      body: jsonEncode(body)
  );
  print('status: ${res.statusCode}');
  print('res body: ${res.body}');
} catch (e) {
  print('sendPushNotificationE: $e');
}}

后台通知接收代码

FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {}

解决办法

  • 优化FCM消息配置
    1. 给android字段添加ttl参数,设置为长有效期,避免消息被系统提前丢弃:
      'android': {
        'priority': 'high',
        'ttl': '86400s' // 设置为24小时有效期
      },
      
    2. 确保voice通知渠道为最高优先级且锁屏可见,创建渠道时需配置:
      await flutterLocalNotificationsPlugin.createNotificationChannel(
        AndroidNotificationChannel(
          'voice',
          'Voice Messages',
          description: 'Receive voice message notifications',
          importance: Importance.max,
          enableLights: true,
          enableVibration: true,
          showBadge: true,
          lockscreenVisibility: NotificationVisibility.public,
        ),
      );
      
  • 适配Android系统电池限制
    部分国产ROM(小米、华为、OPPO等)会强制限制后台进程,需引导用户操作:
    • 关闭应用的「电池优化」,设置为「不优化」
    • 开启应用的「后台弹出界面」权限
    • 将应用加入系统「后台运行白名单」
  • 完善后台处理逻辑
    后台处理函数需完成Firebase初始化,避免系统判定进程无意义而终止:
    Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
      await Firebase.initializeApp();
      print('Background message received: ${message.messageId}');
      // 可添加必要的消息处理逻辑,保持进程活跃
    }
    
  • 切换为纯数据消息投递
    混合类型消息在锁屏后可能被系统限制,改为纯数据消息,由应用自行展示通知:
    // 纯数据消息示例,移除notification字段
    final body = {
      "to": userToken,
      'android': {
        'priority': 'high',
        'ttl': '86400s'
      },
      'data':{
        'type':'voice',
        'id':'1234',
        'voiceUrl': voiceUrl,
        'title': currentName,
        'body': 'New voice message'
      }
    };
    
    之后在后台处理函数中使用本地通知插件展示通知内容。

内容的提问来源于stack exchange,提问作者Muhammad Zain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:53:12