Search code examples
androidflutterbackground-serviceforeground-service

Flutter-Android how to use the camera while the app is in foreground/background


is it possible to use the camera while the app is in the foreground or background? I tried with these two packages flutter_foreground_task and flutter_background_service but i always get this error message once i start the camera stream Unhandled Exception: MissingPluginException(No implementation found for method availableCameras on channel plugins.flutter.io/camera).

class FirstTaskHandler extends TaskHandler {

  void initCamera() async {
    final description = await availableCameras().then(
      (cameras) => cameras.firstWhere(
        (camera) => camera.lensDirection == CameraLensDirection.front,
      ),
    );
    final _cameraController = CameraController(
      description,
      ResolutionPreset.low,
      enableAudio: false,
    );
    await _cameraController.initialize();
    await Future.delayed(const Duration(milliseconds: 500));
    _cameraController.startImageStream((img) async {
      log("Image captures: ${img.width} x ${img.height} -- ${img.format.raw}");
    });
  }

  @override
  Future<void> onStart(DateTime timestamp, SendPort? sendPort) async {
    initCamera();
  }

  @override
  Future<void> onEvent(DateTime timestamp, SendPort? sendPort) async {  }

  @override
  Future<void> onDestroy(DateTime timestamp) async {

  }

  @override
  void onButtonPressed(String id) {

  }
}

Solution

  • I fixed this issue by editing the camera plugin and making the Livestream method work when the app is in the foreground/background. here is the link to the edited plugin edited-flutter-camera-plugin, just note that this version can be crashed in some functionalities because I just edited some files to make it fit my purpose of making the Livestream method works in the foreground