'Android my background camera app lost signal when an other app use the camera

What a tricky question, you will probably want more information..

I'm currently building an app that use the camera in background. This is ethic, and the user has been warned, so don't worry.

I'm using CameraSource from com.google.android.gms.vision.

So the user is free to launch other app and do anything he want to do. Even start other app which access the camera ! Here problems come..

I'm using Flutter as framework.

When user open an other app that use the camera, my app lost signal and Flutter trace only print :

E/Camera  ( 3154): Error 2

Nothing else.. No Exceptions, No traces, Nothing to know here it come from, why or how to handle it !

If you have any idea how to restart the camera untill it's available again, it could save me days.



Solution 1:[1]

You should call cameraController.dispose() when your the app stops (goes to the background or other application opens in top of the app).

Here is the example from the official camera documentation on how they handle app lifecycle for the camera.

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // App state changed before we got the chance to initialize.
    if (controller == null || !controller.value.isInitialized) {
      return;
    }
    if (state == AppLifecycleState.inactive) {
      controller?.dispose();
    } else if (state == AppLifecycleState.resumed) {
      if (controller != null) {
        onNewCameraSelected(controller.description); // Here we reinitialize the cameraController
      }
    }
  }

Here is the link to camera documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Robert Apikyan