参考如下:
https://github.com/googlearchive/android-Camera2Basic
https://www.jianshu.com/p/3440d82545f6
几个概念:
SurfaceView:图像显示的地方
SurfaceHolder:连接图像显示地方与外部的通道,相当于接口
Camera:摄像机
通过把SurfaceView与Camera串联起来,就可以实现视频的播放了。
步骤1:
初始化摄像机,获取前置摄像机和后置摄像机的信息以及ID
void InitCameraInfo(){
int numberOfCameras = Camera.getNumberOfCameras();// 获取摄像头个数
Log.i(tag,"InitCameraInfo:"+numberOfCameras);
for (int cameraId = 0; cameraId < numberOfCameras; cameraId++) {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, cameraInfo);
Log.i(tag,"cameraInfo:"+cameraInfo.facing);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
// 后置摄像头信息
mBackCameraId = cameraId;
mBackCameraInfo = cameraInfo;
} else if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// 前置摄像头信息
mFrontCameraId = cameraId;
mFrontCameraInfo = cameraInfo;
}
}
}
步骤2:先动态申请权限,再打开摄像机,并设置摄像机的显示角度
void OpenCamera(int 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;
}
mCamera = Camera.open(cameraId);
mCameraId = cameraId;
mCameraInfo = cameraId == mFrontCameraId ? mFrontCameraInfo : mBackCameraInfo;
mCamera.setDisplayOrientation(90);
}
步骤3:获取SurfaceHolder,并设置到摄像机里面,然后开启预览,这样就可以查看视频了
SurfaceView surfaceView = findViewById(R.id.surfaceViewId);
mSurfaceHolder = surfaceView.getHolder();
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
步骤4:关闭预览
void CloseCamera(){
if (null != mCamera){
mCamera.release();
mCamera = null;
}
}
整个android预览摄像机的步骤大概就上面几个。
还需要设置申请摄像机权限
<uses-permission android:name="android.permission.CAMERA" />