1

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.

mitr00
  • 28
  • 6
  • Sorry, you might have a misunderstanding here. When app is in foreground it means the app is ACTIVE. Background refers when user is either in home screen or in another app. – Ian Vasco Aug 21 '19 at 14:05
  • I was referring to Android foreground service, but yes, I want to keep the camera open even if the app is in background or closed. – mitr00 Aug 21 '19 at 18:24
  • What API level of android are you working on? Have you tried using lifecycle methods? Have you seen this https://proandroiddev.com/pitfalls-of-a-foreground-service-lifecycle-59f014c6a125? – Nompumelelo Aug 21 '19 at 18:41

1 Answers1

2

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).

Igor Sheko
  • 56
  • 6
  • Thank you for clarifications! I've researched a little bit further and I found that even in native Android Java is a little bit difficult to keep camera open in the background without 'hacks' (on older versions of Android). Didn't know about new privacy limitations, thanks for letting me know. – mitr00 Aug 28 '19 at 12:00