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

Flutter应用终止时接收Firebase消息后注册SIP的解决方案

解决方案:应用终止状态下SIP注册滞后导致呼叫被取消的问题

核心问题在于应用终止时,收到Firebase推送后仅展示了呼叫通知,但未提前完成SIP注册,导致用户接听时SIP客户端无法响应服务器请求,最终被取消呼叫。以下是具体解决步骤:


1. 后台推送触发时预初始化SIP注册

修改Firebase后台消息处理逻辑,在展示呼叫通知前先完成SIP初始化与注册,确保用户接听时SIP已处于就绪状态:

@pragma("vm:entry-point")
Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  if (kDebugMode) {
    print('Message title: ${message.notification?.title}, body: ${message.notification?.body}, data: ${message.data}');
  }
  
  // 优先初始化SIP并等待注册完成
  await initSIPInBackground();
  
  await setupFlutterNotifications();
  await showIncomingCall(message, Uuid().generateV4());
}

// 新增后台SIP初始化方法
Future<void> initSIPInBackground() async {
  final utilisateurs = await SmartDieseDatabase.instance.readAllUtilisateur();
  if (utilisateurs.isNotEmpty && utilisateurs[0].role == 0) {
    // 调用SIPController发起注册
    SIPController.controller.register(listener);
    // 等待注册完成(设置5秒超时,避免无限等待)
    await waitForSIPRegistered();
  }
}

// 等待SIP注册完成的辅助方法
Future<void> waitForSIPRegistered() async {
  int timeoutCount = 0;
  while (SIPController.controller.registerState != RegistrationStateEnum.REGISTERED && timeoutCount < 50) {
    await Future.delayed(const Duration(milliseconds: 100));
    timeoutCount++;
  }
}

2. 接听事件添加注册兜底检查

在用户点击接听按钮时,再次检查SIP注册状态,未完成则先完成注册再应答呼叫:

Future<void> initFirebase() async {
  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);

  RemoteMessage? initialMessage = await FirebaseMessaging.instance.getInitialMessage();

  if(initialMessage != null){
    await firebaseMessagingBackgroundHandler(initialMessage);
  }

  FlutterCallkitIncoming.onEvent.listen((CallEvent? event) async {
    if(event!.event == Event.actionCallAccept){
      // 兜底检查:确保SIP已注册
      if (SIPController.controller.registerState != RegistrationStateEnum.REGISTERED) {
        SIPController.controller.register(listener);
        await waitForSIPRegistered();
      }
      SIPController.controller.signalAnswer();
    }
    if(event.event == Event.actionCallDecline){
      SIPController.controller.signalHangup();
    }
  });
}

3. 平台后台权限配置

确保应用在后台能正常运行SIP相关逻辑:

  • Android:在AndroidManifest.xml中添加权限:
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    
    并将Firebase Messaging服务设置为前台服务,避免被系统杀死。
  • iOS:在Info.plist中开启后台模式:
    <key>UIBackgroundModes</key>
    <array>
      <string>voip</string>
      <string>remote-notification</string>
    </array>
    

内容的提问来源于stack exchange,提问作者Joel Nogues

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 11:25:54