@Override
public void surfaceCreated(final SurfaceHolder holder) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
}
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//在打开摄像头时,你先查看一下设备上摄像头id列表:有可能只有一个,"1"的值:根据的你情况而定
mCameraManager.openCamera("1", new CameraDevice.StateCallback() {
@Override
public void onOpened(final CameraDevice camera) {
try {
// 创建预览需要的CaptureRequest.Builder
final CaptureRequest.Builder previewRequestBuilder =
camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
// 将mSurfaceView的surface作为CaptureRequest.Builder的目标
previewRequestBuilder.addTarget(holder.getSurface());
//如果holder.getSurface().isValid()为false,则会出错;因为你的画布无效导致的问题
if (holder.getSurface().isValid())
//创建相机捕获会话,用于预览的工作。
camera.createCaptureSession(Arrays.asList(holder.getSurface()), new CameraCaptureSession.StateCallback() {