Android Fail to Connect to Camera Service?

2019-04-16 05:51发布

问题:

I am making an app that needs to use the camera flash. My code will be below this post, but I get a java.lang.RuntimeException: Fail to connect to camera service when I try to open the camera. The error comes when the Camera.open(); method is called.

Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();

I have tried restarting the phone, closing all apps, and I still get the same error.

Is there a way to release/close the camera before opening it? I don't know how you would close a null object.

Screen orientation is not a problem as the app is only allowed vertical orientation.

The default camera app works, but not this app.

Error (Full):

    java.lang.RuntimeException: Fail to connect to camera service
        at android.hardware.Camera.native_setup(Native Method)
        at android.hardware.Camera.<init>(Camera.java:319)
        at android.hardware.Camera.open(Camera.java:292)
        at com.bensuniverse.flashlightx.processes.CameraHandler.toggleFlash(CameraHandler.java:21)
        at com.bensuniverse.flashlightx.MainActivity$1.onClick(MainActivity.java:78)
        at android.view.View.performClick(View.java:4106)
        at android.view.View$PerformClick.run(View.java:17052)
        at android.os.Handler.handleCallback(Handler.java:615)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5059)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
        at dalvik.system.NativeStart.main(Native Method)

回答1:

Make sure that you are releasing the camera object properly. If you are trying to reopen camera object if already opened then it will get crashed with the error mentioned by you in stack trace:

Camera camera = Camera.open();
Camera.Parameters parameters = camera.getParameters();
parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
camera.startPreview();  

// Stop camera preview and release it.
camera.stopPreview();
camera.release();


回答2:

I also faced similar issue , reason was my another app uses the camera. but i forget to release the resources in that app. so don't forget to release resources when the app about to close. (onStop / onDestroy()). Camera hardware is a shared resource that must be carefully managed so your application does not collide with other applications that may also want to use it.