我正在制作自定义相机应用。我想实现自定义预览。 只有在第一次显示黑屏后才会打开预览。 如果有人知道为什么请帮助我!
我的相机课程:
public class CamTestActivity extends Activity {
private static final String TAG = "CamTestActivity";
Preview preview;
Camera camera;
int cameraId;
SurfaceView sv;
private int rotation;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
cameraId = Camera.CameraInfo.CAMERA_FACING_BACK;
sv = (SurfaceView) findViewById(R.id.surfaceView);
preview = new Preview(this, sv);
preview.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
((RelativeLayout) findViewById(R.id.layout)).addView(preview);
preview.setKeepScreenOn(true);
// holder = sv.getHolder();
}
@Override
protected void onResume() {
super.onResume();
openCamera(cameraId);
}
public boolean openCamera(int id) {
boolean result = false;
cameraId = id;
releaseCamera();
try {
camera = Camera.open(cameraId);
}
catch (Exception e) {
e.printStackTrace();
}
if (camera != null) {
try {
setUpCamera(camera);
camera.setErrorCallback(new ErrorCallback() {
@Override
public void onError(int error, Camera camera) {
}
});
camera.setPreviewDisplay(preview.mHolder);
camera.startPreview();
result = true;
}
catch (IOException e) {
e.printStackTrace();
result = false;
releaseCamera();
}
}
return result;
}
private void setUpCamera(Camera c) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
rotation = getWindowManager().getDefaultDisplay().getRotation();
int degree = 0;
switch (rotation) {
case Surface.ROTATION_0:
degree = 0;
break;
case Surface.ROTATION_90:
degree = 90;
break;
case Surface.ROTATION_180:
degree = 180;
break;
case Surface.ROTATION_270:
degree = 270;
break;
default:
break;
}
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
// frontFacing
rotation = (info.orientation + degree) % 330;
rotation = (360 - rotation) % 360;
}
else {
// Back-facing
rotation = (info.orientation - degree + 360) % 360;
}
c.setDisplayOrientation(rotation);
Parameters params = c.getParameters();
// showFlashButton(params);
List<String> focusModes = params.getSupportedFlashModes();
if (focusModes != null) {
if (focusModes
.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) {
params.setFlashMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
}
}
params.setRotation(rotation);
}
private void releaseCamera() {
try {
if (camera != null) {
camera.setPreviewCallback(null);
camera.setErrorCallback(null);
camera.stopPreview();
camera.release();
camera = null;
}
}
catch (Exception e) {
e.printStackTrace();
Log.e("error", e.toString());
camera = null;
}
}
}
答案 0 :(得分:-2)
好像你忘了放开你的相机。
将releaseCamera
添加到onPause
@Override
protected void onPause() {
releaseCamera();
super.onPause();
}