Search code examples
androidreact-nativeforeground-servicereact-native-cameravoximplant

Use 'react-native-camera' with the app closed


It is possible to prevent 'react-native-camera' from unmounting when the application goes in foreground?

I've used '@voximplant/react-native-foreground-service' to easily create a foreground service with success, but it seems that 'react-native-camera' is unmounting when the app loses focus.

I know that this is the normal behaviour but I search for a way to scan barcodes with the app in foreground and react to those events.


Solution

  • The issue is caused by ‘react-native-camera’ implementation. This module handles the application state changes. If the application went to the background, it stops the camera itself. As soon as the application is brought to the foreground, it resumes the camera:

    @Override
    public void onHostResume() {
      if (hasCameraPermissions()) {
        if ((mIsPaused && !isCameraOpened()) || mIsNew) {
          mIsPaused = false;
          mIsNew = false;
          start();
        }
      } else {
        RNCameraViewHelper.emitMountErrorEvent(this, "Camera permissions not granted - component could not be rendered.");
      }
    }
    
    @Override
    public void onHostPause() {
      if (mIsRecording) {
        mIsRecordingInterrupted = true;
      }
      if (!mIsPaused && isCameraOpened()) {
        mIsPaused = true;
        stop();
      }
    }
    

    https://github.com/react-native-community/react-native-camera/blob/c62be1e99af9a8a9b44fc8b62744ca08c05bead9/android/src/main/java/org/reactnative/camera/RNCameraView.java#L477-L498

    @voximplant/react-native-foreground-service module only starts a foreground service, but it does not affect other modules and does not invoke any android native camera API. Foreground service is intended to resolve privacy limitations that were introduced in Android 9 (P) (https://developer.android.com/about/versions/pie/android-9.0-changes-all#bg-sensor-access).