startScreenCaptureService static method

Future<bool> startScreenCaptureService()

Start the screen capture foreground service.

On Android 10+: Call this to start the foreground service. On Android 14+: Call this AFTER the user has granted MediaProjection permission (via Helper.requestCapturePermission()).

This method starts the service and waits for it to be fully ready before returning. On Android 14+, the service must call startForeground() with FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION before MediaProjection can be created.

On other platforms, this is a no-op but still returns true.

Returns true if the service started successfully and is ready.

Implementation

static Future<bool> startScreenCaptureService() async {
  if (kIsWeb) {
    // Web doesn't need a foreground service
    return true;
  }

  if (!Platform.isAndroid) {
    return true;
  }

  try {
    debugPrint('QuickRTC: Starting screen capture foreground service');

    // Start the service (returns immediately)
    final result =
        await _channel.invokeMethod<bool>('startScreenCaptureService');

    if (result != true) {
      debugPrint('QuickRTC: Failed to start service');
      return false;
    }

    // Wait for the service to be fully ready (following GetStream's pattern)
    // Poll every 50ms for up to 3 seconds
    final isReady = await _waitForServiceReady();

    _isServiceRunning = isReady;
    debugPrint('QuickRTC: Service ready: $isReady');
    return isReady;
  } on PlatformException catch (e) {
    debugPrint('Failed to start screen capture service: ${e.message}');
    return false;
  } on MissingPluginException {
    // Plugin not registered (e.g., on unsupported platform)
    debugPrint('QuickRTC platform plugin not available');
    return true; // Return true to not block on unsupported platforms
  }
}