How to fix “Fail to connect to camera service” exception in Android emulator

前端 未结 8 1641
情书的邮戳
情书的邮戳 2020-12-01 06:35

I\'m getting a Fail to connect to camera service exception when I run my Android app in the emulator. I\'ve read the various existing posts but none have fixed this. It is

相关标签:
8条回答
  • 2020-12-01 06:48

    Isn't an permission on android 6.x?

    http://developer.android.com/training/permissions/requesting.html

    0 讨论(0)
  • 2020-12-01 06:50

    Using

    if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(CodeScanner.this, new String[]{android.Manifest.permission.CAMERA}, 50);
    }
    

    worked for me

    0 讨论(0)
  • 2020-12-01 06:54

    If you periodically got a white screen instead your view of camera - use:

    private void releaseCameraAndPreview() {
            if (mCamera != null) {
                mCamera.setPreviewCallback(null);
                mCameraView.getHolder().removeCallback(mCameraView);
                mCamera.release();
                mCamera = null;
            }
        }
    

    and put it here

    try {
                releaseCameraAndPreview();
                mCamera = getCameraInstance();
            }...
    

    and here

    @Override
        protected void onPause() {
            super.onPause();
            releaseCameraAndPreview();
        }
    
    0 讨论(0)
  • 2020-12-01 06:57

    From the Android Developers Docs:

    Calling Camera.open() throws an exception if the camera is already in use by another application, so we wrap it in a try block.

    Try wrapping that code in a try catch block like so:

    try {
        releaseCameraAndPreview();
        if (camId == 0) {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
        }
        else {
            mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
        }
    } catch (Exception e) {
        Log.e(getString(R.string.app_name), "failed to open Camera");
        e.printStackTrace();
    }
    

    Then add this function somewhere:

    private void releaseCameraAndPreview() {
        myCameraPreview.setCamera(null);
        if (mCamera != null) {
            mCamera.release();
            mCamera = null;
        }
    }
    
    0 讨论(0)
  • 2020-12-01 06:58

    OP mentions this in his question, but my issue was I forgot to enable camera emulation in my AVD emulator settings:

    0 讨论(0)
  • 2020-12-01 06:58

    If you are using surface View and using code like this`

     Observable.create(CameraUtils.getCameraOnSubscribe())
                        .subscribeOn(Schedulers.newThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(camera -> {
    
                     mCamera = camera.open();
    ...    
    }};
    

    Then replace mCamera=camera;

    0 讨论(0)
提交回复
热议问题