当第二次调用 SurfaceHolder.Callback 的 surfaceCreated 方法时,相机对象出现问题,我的意思是:
我在我的活动中的 onResume 方法中创建了一个对象相机,这可以很好地显示预览显示,但是当我的活动暂停时,表面视图被破坏,我必须释放相机对象,然后如果我的活动进入 onresume android throws我的相机对象中有一个 nullPointerException。
我不确定为什么会发生这种情况,我将注释用于调试每个方法并查看会发生什么,显然一切都很好,只有在相机对象变为 null 的 surfaceCreated 方法中。
这是我的课:
public class CameraRecord implements SurfaceHolder.Callback{
public static final int BACK_CAMERA = 1;
public static final int FRONT_CAMERA = 2;
//private SurfaceView surface;
private SurfaceHolder holder;
private Camera camera;
public CameraRecord(SurfaceView surface){
// this.surface = surface;
holder = surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Log.e("CameraRecord","constructor");
}
public void openCamera(int wichCamera) throws Exception {
if (wichCamera == BACK_CAMERA)
camera = Camera.open();
else {
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
int cameraCount = Camera.getNumberOfCameras();
for (int i = 0; i < cameraCount; i++ ) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT)
try {
camera = Camera.open(i);
Log.e("CameraRecord","camera is CAMERA_FACING_FRONT " + cameraInfo.toString());
} catch (RuntimeException e) {
e.printStackTrace();
}
}
}
if (camera == null)
Log.e("CameraRecord","openCamera camera is null");
else
Log.e("CameraRecord","openCamera camera is not null");
}
public void start() throws IOException {
camera.startPreview();
}
public void stop() {
camera.stopPreview();
Log.e("CameraRecord","stop camera");
}
public void release() {
camera.release();
camera = null;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
Log.e("CameraRecord", "surfaceChanged");
try {
start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// if (holder == null)
// Log.e("CameraRecord","holder is null");
// else
// Log.e("CameraRecord","holder is not null");
try {
if (camera == null)
Log.e("CameraRecord","camera is null");
else
Log.e("CameraRecord","camera is not null");
camera.setPreviewDisplay(holder);
// start();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e("CameraRecord", "surfaceDestroyed");
stop();
release();
}
}