I create an application that takes a photo from the Service from the back of the phone’s camera. But at runtime, I get an exception:

java.lang.RuntimeException: Fail to connect to camera service

Here is the source code for my Service :

 @SuppressWarnings("deprecation") public class I2 extends Service { byte[] i1; @Override public IBinder onBind(Intent i1) { return null; } @Override public void onStart(Intent i1, int i2) { new Thread(new i1()).start(); return; } private class i1 implements Runnable { private byte[] i1 = null; @Override public void run() { while (true) { try { Camera i1 = Camera.open(); i1.setPreviewDisplay(new SurfaceView(I2.this).getHolder()); i1.startPreview(); i1.takePicture(null, null, new PictureCallback() { @Override public void onPictureTaken(byte[] i1, Camera i2) { I2.this.i1 = i1; //получаю byte картинки i2.stopPreview(); i2.release(); } }); } catch (Exception e1) { Log.v("", "lnp_ " + e1.toString()); } try { Thread.sleep(10000); } catch (InterruptedException e1) { } } } } } 

In the file AndroidManifest.xml permission for the camera added:

 <uses-permission android:name="android.permission.CAMERA" /> 

On the Internet, I found examples of projects with the camera and found the following: https://examples.javacodegeeks.com/android/core/hardware/camera-hardware/android-camera-example/ but still the same error! Tell me how to fix it?

  • I started using cheap Android phones in my video surveillance system instead of expensive video cameras, which cost up to 20 thousand rubles. So I am not going to do any vulnerabilities and tricks. - nick
  • Unfortunately, the same error. The exception crashes in the following line: Camera i1 = Camera.open(); . I tried to add arguments 0 , 1 , 2 ... to the open method. - nick
  • one
    Camera permissions requested by developer.android.com/training/permissions/requesting.html ? Which returns Camera.getNumberOfCameras(); ? - Yura Ivanov
  • @YuraIvanov, and you know, I did it. Indeed, after this team earned a virtual phone. Now I will try to test it on the usual. - nick

1 answer 1

Before you access the camera, and even more so to take pictures, you need to enter this line here:

 Camera.getNumberOfCameras(); 

Thanks to @Yura Ivanov.


If you are programming on an Android emulator version 5.0 and higher, then you need to go to Settings -> Applications -> "Your application name" -> Permissions -> Camera, check the box