几个概念:

SurfaceView:图像显示的地方
SurfaceHolder:连接图像显示地方与外部的通道,相当于接口
CameraManager:摄像机的管理类
CameraDevice:具体相机的操作类

 

调用流程:

1、获取摄像机管理类:mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

2、打开某个具体的摄像机:mCameraManager.openCamera(cameraId, stateCallback, null);

3、在打开成功的回调里面,创建预览请求:mCameraDevice.createCaptureSession

4、在创建预览请求的回调里面,设置预览模式:mCameraCaptureSession.setRepeatingRequest

大概分为以上4个步骤

实现代码如下:

package com.example.grammartest;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import java.io.IOException;
import java.util.Arrays;
import android.widget.Toast;

public class Camera2Activity extends AppCompatActivity {

    String tag = "Camera2Activity";
    private static final String[] REQUIRED_PERMISSIONS = {Manifest.permission.CAMERA};
    private static final int REQUEST_PERMISSIONS_CODE = 1;

    private CameraManager mCameraManager;//摄像头管理器
    CameraDevice mCameraDevice;
    String FRONTId, BACKId;

    private SurfaceHolder mSurfaceHolder;
    private CameraCaptureSession mCameraCaptureSession;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera2);
        InitView();
        InitCameraInfo();
    }

    void InitView() {
        Button ViewBt = findViewById(R.id.Camera2PlayBt);
        Button ViewCloseBt = findViewById(R.id.Camera2CloseBt);
        SurfaceView surfaceView = findViewById(R.id.Camera2surfaceViewId);
        mSurfaceHolder = surfaceView.getHolder();

        ViewBt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i(tag,"setOnClickListener");
                    OpenCamera(BACKId);

            }
        });

        ViewCloseBt.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                CloseCamera();
            }
        });
    }

    void InitCameraInfo() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
            String[] cameraList = new String[0];
            try {
                cameraList = mCameraManager.getCameraIdList();
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
            for (String item : cameraList) {
                Log.i(tag, "Camera2Activity:" + item);
                String FrontItem = CameraCharacteristics.LENS_FACING_FRONT + "";
                String BackItem = CameraCharacteristics.LENS_FACING_BACK + "";
                if (item.equals(FrontItem)) {
                    FRONTId = item;
                } else if (item.equals(BackItem)) {
                    BACKId = item;
                }

            }

        }

    }

    void OpenCamera(String cameraId) {
        if (false == isRequiredPermissionsGranted()) {
            Log.i(tag, "isRequiredPermissionsGranted false");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(REQUIRED_PERMISSIONS, REQUEST_PERMISSIONS_CODE);
            }
            return;
        }
        try {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mCameraManager.openCamera(cameraId, stateCallback, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }

    }
    void  CloseCamera(){
        if (null != mCameraDevice){
            mCameraDevice.close();
            mCameraDevice = null;
        }
    }
    private void takePreview() {
        try {

            // 创建CameraCaptureSession,该对象负责管理处理预览请求和拍照请求
            mCameraDevice.createCaptureSession(Arrays.asList(mSurfaceHolder.getSurface()), new CameraCaptureSession.StateCallback() // ③
            {
                @Override
                public void onConfigured(CameraCaptureSession cameraCaptureSession) {
                    if (null == mCameraDevice) return;
                    // 当摄像头已经准备好时,开始显示预览
                    mCameraCaptureSession = cameraCaptureSession;
                    try {
                        // 创建预览需要的CaptureRequest.Builder
                        final CaptureRequest.Builder previewRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
                        // 将SurfaceView的surface作为CaptureRequest.Builder的目标
                        previewRequestBuilder.addTarget(mSurfaceHolder.getSurface());
                        // 自动对焦
                        previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
                        // 打开闪光灯
                        previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
                        // 显示预览
                        CaptureRequest previewRequest = previewRequestBuilder.build();
                        mCameraCaptureSession.setRepeatingRequest(previewRequest, null, null);
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onConfigureFailed(CameraCaptureSession cameraCaptureSession) {
                    Toast.makeText(Camera2Activity.this, "配置失败", Toast.LENGTH_SHORT).show();
                }
            }, null);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
    private final CameraDevice.StateCallback stateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(CameraDevice camera) {
            mCameraDevice = camera;
            Log.i(tag, "CameraDevice onOpened");
            takePreview();
        }


        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {
            Log.i(tag, "CameraDevice Disconnected");
        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {
            Log.e(tag, "CameraDevice Error");
        }
    };

    private boolean isRequiredPermissionsGranted() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }
}