Search code examples
androidandroid-camera2android-9.0-pie

android,,camera can't be accessed when screen is off or app is not focusd on screen


First i use CameraManager.open(cameraid,StateCallbackObject,handler) to use camera,and then i turn off the screen or switch screen to display phone desktop or other app,after around 1 minute camera access is abrupted and onError method in StateCallbackObject is invoked.

If i keep my screen on and keep the app displaying on screen,it can keep using camera without interruption or error.

my question is : how can i keep the camera opened after screen off or app is not focused.

Excerpt of the code:

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      callback = new AvailabilityCallback(){
        @Override
        public void onCameraAvailable(String cameraId){
            iscamerafree = true;
        }

        @Override
        public void onCameraUnavailable(String cameraId){
            iscamerafree = false;
        }

      };

      new CameraHolder();
    }
}

CameraHolder.java

public class CameraHolder {
  CameraHolder(){
    while(iscamerafree==true){
      manager.openCamera(cameraid, new CameraDevice.StateCallback() {
         @Override
         public void onOpened(CameraDevice camera) {
           //do some stuff
         }

         @Override
         public void onDisconnected(CameraDevice camera) {}

         @Override
         public void onError(CameraDevice camera, int error) {
            //after screen off or app not focused on screen for 1 min,this is invoked
         }
      },handler);
    }
  }
}

Solution

  • If i keep my screen on and keep the app displaying on screen,it can keep using camera without interruption or error.

    You cannot. This behavior is intentional and background apps are not able to access neither the camera nor microphone. Your app must stay in foreground for these sources to be available while running on Android 9 (and most likely newer as well).

    See "Privacy & Security" on https://source.android.com/setup/start/p-release-notes:

    Privacy enhancements: Android 9 safeguards privacy in a number of new ways. Now, Android will restrict access to your phone's microphone, camera, or other sensors when an app is idle or running in the background. (If an app does need to access a sensor, it will show a persistent notification on your phone.) Android 9 also brings important improvements that protect all web communications and offer private web surfing.