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.
}
}
To create the second activity, follow these steps: In the Project window, right-click the app folder and select New > Activity > Empty Activity. In the Configure Activity window, enter "DisplayMessageActivity" for Activity Name. Leave all other properties set to their defaults and click Finish.
An activity provides the window in which the app draws its UI. This window typically fills the screen, but may be smaller than the screen and float on top of other windows. Generally, one activity implements one screen in an app.
Android devices can have multiple cameras, for example a back-facing camera for photography and a front-facing camera for video calls. Android 2.3 (API Level 9) and later allows you to check the number of cameras available on a device using the Camera.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With