我正在编写一个访问相机的程序。它工作了一段时间,但现在是相机API抛出异常,因为当我尝试打开它时,相机仍在使用中。我认为这是因为我在onPause、onResume和我使用它的地方没有正确处理它。下面是我的代码:
@Override
protected void onResume(){
if (!getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
} else {
try {
if (camera != null) {
camera.release();
camera = null;
}
camera = Camera.open(cameraId);
try {
camera.setPreviewTexture(cameraTexture);
}
catch(IOException e){
Log.i("CameraHome", "could not set camera preview");
}
}
catch (Exception e){
}
}
}
super.onResume();}
暂停:
@Override
public void onPause(){
stopLocationUpdates();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong("timeLeft", timeLeft);
editor.putBoolean("lockedOut", lockedOut);
editor.apply();
if (camera != null) {
camera.release();
camera = null;
}
super.onPause();
}
使用中:
//Take picture
camera.startPreview();
camera.takePicture(null, null,
new PhotoHandler(getApplicationContext()));
camera.stopPreview();
camera.release();
知道我做错了什么吗?每次我重新启动应用程序时,它都会抛出一个异常,说相机正在使用中,即使我启动默认的相机应用程序并关闭它。
编辑:正在访问相机,但我的回调(在PhotoHandler中的onPictureTake)从未被调用,就好像照片没有被正确捕获一样。
证明这段代码是有效的。必须卸载、重新启动并重新安装。然后我的onPictureTake回调没有被调用。我想这是因为我打stopPreview太早了。我把它移到我的onPause上,并在takePicture通话后取消了发布通话。现在工作正常