0

I am having a problem using the camera in Android.

Developing on API 25 Nougat 7.1.1 SDK. Min target SDK is set to 15.

It throws error everytime upon calling:

Camera camera = Camera.open();

with the error "RuntimeException: Fail to connect to camera service", which can be seen from my emulator (Nexus 5X API 25 Android 7.1.1)

Testing on a REAL DEVICE (Android 5.1.1) the camera features does not work either - exactly the same problem.

Here is the code:

import android.hardware.Camera;

...

boolean hasCamera = false;

private boolean hasCamera(Context context) {
        return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
    }

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    hasCamera = hasCamera(this);
    if(!hasCamera) {
        takePhotoButton.setText("No Camera Found");
        takePhotoButton.setEnabled(false);
    }
}

private class TakePhotoButtonListener implements View.OnClickListener {
    @Override
    public void onClick(View v) {
        if(hasCamera) {
            try {
                Camera camera = Camera.open();
                camera.startPreview();
                camera.takePicture(
                        null,
                        null,
                        new CameraPictureCallbackJPEG());
            } catch (Exception e) {
                Log.i("Error", e.getMessage());
            }
        }
    }
}

The camara is indeed detected (hasCamera == true).

I'm not using the Camera2 (from API 21) onwards because I'd like my app to be work on API 15 onwards.

I'e tried many answers here but nothing worked. Please advise!

ikevin8me
  • 4,253
  • 5
  • 44
  • 84

1 Answers1

1

Please add following permissions to your Manifest file, if these are not added.

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

Important note: This is happening because you've opened Camera at first launch and after that you haven't release it's resources. make sure you should do this

camera.stopPreview();
camera.release();
camera = null;

You have to do above process of cleaning and releasing resources when you are done with using camera.

Hope this helps.

MobileEvangelist
  • 2,583
  • 1
  • 25
  • 36