我有一个 QR 扫描仪 Activity ,成功扫描代码后将移至下一个 Activity 。但是,我想要一个后退按钮来返回 Activity (如果这个结果可能不正确)。然而,当我返回 Activity 时,结果仍然被存储,并且扫描仪不扫描代码。
如何重新启动条形码检测器?我应该重写 onPause/onResume 吗?以下是迄今为止我的代码。
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
最佳答案
在您的情况下,在您的 Activity 的 onResume() 方法中调用 setupBarcodeDetector() 方法。 为了更好地优化,请在 onCreate() 方法中进行初始化,并在 onPause() 和 onResume() 方法中开始和停止扫描。
关于java - 当我返回 Activity 时,如何重新启动 BarcodeDetector 以获得新结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58498856/