1

My app controls the camera and recently there have been a lot of crash reports by devices that cannot open the camera. Pressing the back button releases the camera but also disables the background mode. Pressing the home button doesn't release the camera, causes a crash when opening camera, and yet enables background mode.

How can I release the camera when the camera app itself is opened?

Skyfall
  • 35
  • 7

2 Answers2

1

When you use android hardware camera in your android application you should release it so other application or your application can use it. It is good practice to release camera before moving to another activity in your app.

Use below code -

protected void onDestroy(){

  if(camera!=null){
        camera.stopPreview();
        camera.setPreviewCallback(null);

        camera.release();
        camera = null;
    }
}

above code will release hardware camera,which you was open using Camera.open(); method.

and if you have your custom preview then you have to use in side your surfaceDestroyed method -

public void surfaceDestroyed(SurfaceHolder holder) {

    if(camera!=null){
        camera.stopPreview();
        camera.setPreviewCallback(null);

        camera.release();
        camera = null;
    }
}

Hope it will help you.

La bla bla
  • 8,558
  • 13
  • 60
  • 109
Ravi Bhandari
  • 4,682
  • 8
  • 40
  • 68
0

It is considered safe practice to release camera when onPause() of the relevant Activity is invoked. In line with that, I'd encourage not to pass active Camera object from one Activity to another. I often use Fragments to change the UI while still keeping the Camera active.

There are some special cases, when the app must use the camera even after onPause(), see e.g. Detect when another app tries to use the camera. Not in all cases this is possible, but never it is easy to handle.

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307