Android camera2 API CameraDevice

android camer2 api open cameradevice

Describes how to open the android camera2 api CameraDevice

Part 3 of the camera2 API tutorial series which concentrates opening the android camera2 api cameradevice. This is needed before CaptureRequests & CameraCaptureSessions can be started.

Code available on github

You can download the code by cloning this url from github and the code changes are under the Tag “cameradevice”

Or else you can run this command

git clone --branch cameradevice

Create CameraDevice & CameraDevice.StateCallback methods


private CameraDevice mCameraDevice;
private CameraDevice.StateCallback mCameraDeviceStateCallback
        = new CameraDevice.StateCallback() {
    public void onOpened(CameraDevice camera) {
        mCameraDevice = camera;
        Toast.makeText(getApplicationContext(), "Camera Opened!", Toast.LENGTH_SHORT).show();

    public void onDisconnected(CameraDevice camera) {
        mCameraDevice = null;

    public void onError(CameraDevice camera, int error) {
        mCameraDevice = null;

Create openCamera method

private void openCamera() {
        CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
        try {
            cameraManager.openCamera(mCameraId, mCameraDeviceStateCallback, null);
        } catch (CameraAccessException e) {

Call the openCameraMethod when the surface texture is available

                public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                    setupCamera(width, height);

Run & check the CameraDevice is opened successfully

About The Author

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>