startForegroundService method

Future<void> startForegroundService({
  1. NECallType? callType,
})

启动前台 Service

callType 通话类型。传入时按该类型校验权限并启动对应 Service; 为空时(群呼场景),根据当前已授予的权限决定启动什么类型的 Service。

Implementation

Future<void> startForegroundService({NECallType? callType}) async {
  if (!CallState.instance.isStartForegroundService) {
    CallKitUILog.i(
      _tag,
      'CallManager startForegroundService: callType=$callType',
    );

    NECallType serviceType;

    if (callType != null) {
      // 单呼场景:按通话类型校验权限
      var hasRequiredPermissions = false;

      if (callType == NECallType.audio) {
        hasRequiredPermissions = await Permission.has(
          permissions: [PermissionType.microphone],
        );
        CallKitUILog.i(
          _tag,
          'startForegroundService: audio call, hasMicrophonePermission = $hasRequiredPermissions',
        );
      } else if (callType == NECallType.video) {
        hasRequiredPermissions = await Permission.has(
          permissions: [PermissionType.microphone, PermissionType.camera],
        );
        CallKitUILog.i(
          _tag,
          'startForegroundService: video call, hasMicrophoneAndCameraPermissions = $hasRequiredPermissions',
        );
      } else {
        hasRequiredPermissions = true;
      }

      if (!hasRequiredPermissions) {
        CallKitUILog.i(
          _tag,
          'startForegroundService: permission denied, cannot start foreground service',
        );
        return;
      }
      serviceType = callType;
    } else {
      // 群呼场景:根据已授予的权限决定 Service 类型
      final hasMicrophone = await Permission.has(
        permissions: [PermissionType.microphone],
      );
      final hasCamera = await Permission.has(
        permissions: [PermissionType.camera],
      );
      CallKitUILog.i(
        _tag,
        'startForegroundService: detecting permissions, hasMic=$hasMicrophone, hasCam=$hasCamera',
      );

      if (hasMicrophone && hasCamera) {
        serviceType = NECallType.video;
      } else if (hasMicrophone) {
        serviceType = NECallType.audio;
      } else {
        CallKitUILog.i(
          _tag,
          'startForegroundService: no microphone permission, skip',
        );
        return;
      }
    }

    NECallKitPlatform.instance.startForegroundService(serviceType);
    CallState.instance.isStartForegroundService = true;
    CallKitUILog.i(
      _tag,
      'startForegroundService: started with serviceType=$serviceType',
    );
  }
}