step1 获取一个相机实例
/** A safe way to get an instance of the Camera object. */
public static Camera getCameraInstance(int id) {
Camera c = null;
try {
c = Camera.open(id); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
step2 检测设备是否存在相机
/**
* 检测设备是否存在相机
*/
private boolean checkCameraHardware(Context c) {
if (c.getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}
step2 创建一个SurfacceView用于显示相机画面
public class SufaceCamera extends SurfaceView implements SurfaceHolder.Callback {
android.hardware.Camera mCamera;
private SurfaceHolder mSurfaceHolder;
public SufaceCamera(Context context, android.hardware.Camera camera) {
super(context);
this.mCamera = camera;
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
try {
mCamera.setDisplayOrientation(90);
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
if (mSurfaceHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(mSurfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
}
}
}
step3 创建实例开启相机
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cameralayout);
ButterKnife.bind(this);
if (checkCameraHardware(getApplication())) {
cameraInstance = getCameraInstance(Camera.CameraInfo.CAMERA_FACING_FRONT);
SufaceCamera sufaceCamera = new SufaceCamera(this, cameraInstance);
submenuarrow.addView(sufaceCamera,0);
}
}