Search code examples
androidandroid-camera

How to release camera after activity ends in Android?


I am working on an application that requires to scan a QR code and click pictures, but sometimes it so happens that the camera application crashes and it says that the Android Camera has stopped working and the device needs to be restarted for proper functioning.

I want to be able to release the camera from my activity itself to avoid it crashing later in any case. Help needed!

CODE FOR SCANNING:

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    try{
       Intent intent = new Intent("com.google.zxing.client.android.SCAN");
       intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
       startActivityForResult(intent, 0);
    }catch(Exception e){
         // ERROR
    }
} //End of onCreate

public void onActivityResult(int requestCode, int resultCode, Intent intent){
   if (requestCode == 0){
      if (resultCode == RESULT_OK){
         String contents = intent.getStringExtra("SCAN_RESULT");
         showPass(contents);
      }
      else if (resultCode == RESULT_CANCELED){
         showFail();
      } 
   } // End of If
} //End of onActivityResult

CODE FOR CLICKING PICTURE :

public void takephoto(View v){
     Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
     startActivityForResult(cameraIntent, CAMERA_REQUEST);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if (requestCode == CAMERA_REQUEST){
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        //some action.
    }
}

Solution

  • Put Below code in your onDestroy method of your activity:

    protected void onDestroy(){
    
    if(camera!=null){
                camera.stopPreview();
                camera.setPreviewCallback(null);
    
                camera.release();
                camera = null;
            }
    
    
    }
    

    If you are using separate Preview class then add below code in that:

    public void surfaceDestroyed(SurfaceHolder holder) {
    
            if(camera!=null){
                camera.stopPreview();
                camera.setPreviewCallback(null);
    
                camera.release();
                camera = null;
            }
    
        }