确保已经在 Manifest.xml 文件中添加相机权限。
确保正确设置相机预览视图的大小。
在 SurfaceView 或 TextureView 上设置 SurfaceHolder 或 SurfaceTexture 作为相机预览的输出目标。
确保正确实现相机回调,以及在合适的时间调用依赖于相机的方法,比如停止预览或释放相机。
以下是一段基本的代码示例,用于设置相机预览的 SurfaceView:
public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
private Camera camera;
public CameraPreview(Context context, Camera camera) {
super(context);
this.camera = camera;
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
SurfaceHolder holder = getHolder();
holder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the preview.
try {
camera.setPreviewDisplay(holder);
camera.startPreview();
} catch (IOException e) {
Log.d("CameraPreview", "Error setting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (getHolder().getSurface() == null){
// preview surface does not exist
return;
}
// stop preview before making changes
try {
camera.stopPreview();
} catch (Exception e){
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or