How to free the camera after shutdown in Android?

I’m working on an application that requires you to scan a QR code and click on an image, but sometimes it happens that the camera application crashes and it says that the Android camera has stopped working and you need to restart the device to work correctly.

I want to free the camera from my very activity in order to avoid its failure later in any case. Need help!

SCAN CODE:

@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 } } 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(); } } } 

CODE FOR CLIMATE IMAGES:

  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. } } 
+6
source share
1 answer

Put the code below 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 a separate preview class, add the code below:

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

Source: https://habr.com/ru/post/945651/


All Articles