【发布时间】:2016-02-19 01:15:35
【问题描述】:
我有一个 android 活动,它使用表面视图显示实时相机预览。一切正常,但是当我按下手机上的锁定按钮然后解锁手机时,或者当来自另一个活动(例如蓝牙传输或来电)的对话框覆盖我的相机预览时,应用程序崩溃。我怀疑这是我的onResume() 或onPause() 活动的问题,因为我收到错误“释放()之后调用的方法”。但是,我不确定如何解决这个问题。
相机活动:
@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
}
}
【问题讨论】:
-
mCamera.release()不会使mCamera为空。发布后将null分配给mCamera。
标签: java android android-camera onresume onpause