android,当屏幕关闭或应用程序未聚焦在屏幕上时无法访问相机

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

先用CameraManager.open(cameraid,StateCallbackObject,handler)用相机,然后关屏 或切换屏幕以显示 phone 桌面或其他应用程序,大约 1 分钟后相机访问突然中断并调用 StateCallbackObject 中的 onError 方法。

如果我保持屏幕开启并保持应用程序显示在屏幕上,它可以继续使用相机而不会中断或出错。

我的问题是:如何在屏幕关闭或应用程序未聚焦后保持相机打开。

代码摘录:

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);
    }
  }
}

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

你不能。此行为是故意的,后台应用程序无法访问摄像头和麦克风。 运行 在 Android 9(而且很可能更新)时,您的应用必须保持在前台才能使用这些来源。

参见 https://source.android.com/setup/start/p-release-notes 上的 "Privacy & Security":

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.