I have a QR scanner activity which moves to the next activity on successful code scan. However, I want to have a back button to return to the activity (if this result may be incorrect). When I return to the activity, however, the result is still stored and the scanner is not scanning for codes.
How can I restart the barcode detector? Should I override onPause/onResume? Below is my code thus far.
private void setupBarcodeDetector() {
barcodeDetector =
new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
cameraSource =
new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(640, 480)
.build();
surfaceView
.getHolder()
.addCallback(
new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(
getApplicationContext(), Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(holder);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(
SurfaceHolder holder, int format, int width, int height) {
// LEAVE EMPTY
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(
new Detector.Processor<Barcode>() {
@Override
public void release() {
// LEAVE EMPTY
}
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if (qrCodes.size() != 0) {
barcodeDetector.release();
resultQRtv.post(
new Runnable() {
@Override
public void run() {
Vibrator vibrator =
(Vibrator)
getApplicationContext()
.getSystemService(
Context
.VIBRATOR_SERVICE);
vibrator.vibrate(500);
successPrompt.setVisibility(View.VISIBLE);
allGoodTv.setVisibility(View.VISIBLE);
// Loading animation - to be changed with specific
// animation
if (dialog == null) {
dialog =
new ProgressDialog(
QRCodeScannerActivity.this);
dialog.setCancelable(false);
dialog.setMessage("Registering...");
}
dialog.show();
Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
@Override
public void run() {
// On successful scan, go to the required
// activity
Intent
goToAdminAccountConfirmationActivity =
new Intent(
QRCodeScannerActivity
.this,
AdminAccountConfirmSettings
.class);
startActivity(
goToAdminAccountConfirmationActivity);
// Remove the prompts in case the user
// returns to this activity
dialog.dismiss();
successPrompt.setVisibility(View.GONE);
allGoodTv.setVisibility(View.GONE);
}
},
1500);
}
});
}
}
});
} // setupBarcodeDetector
In your case call setupBarcodeDetector() method inside onResume() method of your activty. for batter optimisation do the initialization in onCreate() method and start and stop scanning inside onPause() and onResume() methods.