Search code examples
javaandroidandroid-cameraonresumeonpause

Android App Crashes when paused


I have an android activity which displays a live camera preview using a surfaceview. Everything works fine, however when I press the lock button on my phone and then unlock my phone or when a dialog box from another activity (example bluetooth transfer, or incoming call) overlays my camera preview the app crashes. I suspect this is a problem with my onResume() or onPause() activities as I get an error "method called after release()". However, I am unsure how to fix this.

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
    }

}


Solution

  • Try adding this line to your onPause():

    camera_view.removeView(mCameraView);