我有一个Android活动,它使用surfaceview显示实时相机预览。一切正常,但是当我按下手机上的锁定按钮然后解锁我的手机或当另一个活动的对话框(例如蓝牙传输或来电)覆盖我的相机预览时,应用程序崩溃。我怀疑这是我的onResume()
或onPause()
活动的问题,因为我收到错误"在release()"之后调用的方法。但是,我不确定如何解决这个问题。
CAMERA ACTIVITY:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera_screen);
setStatusBarColor();
Display display = getWindowManager().getDefaultDisplay();
final int height = display.getHeight();
session = new SessionManager(getApplicationContext());
try {
mCamera = Camera.open();//you can use open(int) to use different cameras
} catch (Exception e) {
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if (mCamera != null) {
mCameraView = new CameraPreview(this, mCamera);//create a SurfaceView to show camera data
FrameLayout camera_view = (FrameLayout) findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
//rotate preview
mCamera.setDisplayOrientation(90);
//rotate camera
Camera.Parameters p = mCamera.getParameters();
p.setRotation(90);
mCamera.setParameters(p);
}
@Override
protected void onPause() {
super.onPause();
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCameraView.getHolder().removeCallback(mCameraView);
mCamera.release();
}
}
@Override
public void onResume() {
super.onResume();
// Get the Camera instance as the activity achieves full user focus
if (mCamera == null) {
initializeCamera(); // Local method to handle camera initialization
}
}
protected void initializeCamera(){
// Get an instance of Camera Object
try{
mCamera = Camera.open();//you can use open(int) to use different cameras
} catch (Exception e){
Log.d("ERROR", "Failed to get camera: " + e.getMessage());
}
if(mCamera != null) {
mCameraView = new CameraPreview(this, mCamera);//create a SurfaceView to show camera data
FrameLayout camera_view = (FrameLayout)findViewById(R.id.camera_view);
camera_view.addView(mCameraView);//add the SurfaceView to the layout
}
}
答案 0 :(得分:1)
尝试将此行添加到onPause():
camera_view.removeView(mCameraView);
答案 1 :(得分:0)
onPause(){
...
mCamera.release(); // close mCamera, but not set it to null
//mCamera = null; // you need reset mCamera to trigger init method;
}
onResume(){
...
initializeCamera();// need mCamera == null
}
//If you find other problems.
//Add some codes in the initializeCamera().
{
//mCamera.setPreviewCallback("something");
//mCameraView.getHolder().addCallback(mCameraView);
}
//as onPause do.