In this case, building against API 23, so permissions are handled too.

You must add in the Manifest the following permission (wherever the API level you’re using):

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

We’re about to create an activity (Camera2Activity.java) that fills a TextureView with the preview of the device’s camera.

The Activity we’re going to use is a typical AppCompatActivity:

public class Camera2Activity extends AppCompatActivity {

Attributes (You may need to read the entire example to understand some of it)

The MAX_PREVIEW_SIZE guaranteed by Camera2 API is 1920x1080

private static final int MAX_PREVIEW_WIDTH = 1920;
private static final int MAX_PREVIEW_HEIGHT = 1080;

TextureView.SurfaceTextureListener handles several lifecycle events on a TextureView. In this case, we’re listening to those events. When the SurfaceTexture is ready, we initialize the camera. When it size changes, we setup the preview coming from the camera accordingly

private final TextureView.SurfaceTextureListener mSurfaceTextureListener
        = new TextureView.SurfaceTextureListener() {

    @Override
    public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) {
        openCamera(width, height);
    }

    @Override
    public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) {
        configureTransform(width, height);
    }

    @Override
    public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
        return true;
    }

    @Override
    public void onSurfaceTextureUpdated(SurfaceTexture texture) {
    }

};

A CameraDevice represent one physical device’s camera. In this attribute, we save the ID of the current CameraDevice

private String mCameraId;

This is the view (TextureView) that we’ll be using to “draw” the preview of the Camera

private TextureView mTextureView;

The CameraCaptureSession for camera preview

private CameraCaptureSession mCaptureSession;

A reference to the opened CameraDevice

private CameraDevice mCameraDevice;

The Size of camera preview.