我已经使用Google Vision API实现了QR扫描仪(QRScanner类)。一旦检测到一个值,它就会使用Intents传递给另一个活动(Info类)。问题是,一旦扫描了QR码,Info类就会多次打开。我想限制QRScanner类仅获取一个QR值,而Info分类仅打开一次。
QRScanner类
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qr_scanner);
cameraPreview = (SurfaceView) findViewById(R.id.camera_surface);
qrResult = (TextView) findViewById(R.id.scannerResult);
setupCamera();
}
private void setupCamera() {
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this).setBarcodeFormats(Barcode.QR_CODE).build();
final CameraSource cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setAutoFocusEnabled(true)
.setRequestedPreviewSize(1600, 1024)
.build();
cameraPreview.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(QrScanner.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
try {
cameraSource.start(cameraPreview.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
@Override
public void release() {
}
@Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrCodes = detections.getDetectedItems();
if(qrCodes.size()>0)
{
qrResult.post(new Runnable() {
@Override
public void run() {
qrResult.setText(qrCodes.valueAt(0).displayValue);
Intent intent = new Intent(QrScanner.this,Info.class);
intent.putExtra(QR_CODE,qrCodes.valueAt(0).displayValue);
startActivity(intent);
}
});
}
}
});
}
信息类
Intent intent = getIntent();
QRCODE = (String) intent.getStringExtra(QrScanner.QR_CODE);
DB = FirebaseDatabase.getInstance();
ref = DB.getReference().child("Animals").child(QRCODE);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
String DBAnimalClass = dataSnapshot.child("class").getValue().toString();
String DBAnimalFamily = dataSnapshot.child("family").getValue().toString();
String DBAnimalOrder = dataSnapshot.child("order").getValue().toString();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
当前,一旦检测到QR,就会多次调用Info类。我希望QRScanner仅获得一个值,而Info类仅获得一次调用
答案 0 :(得分:0)
开始活动之前,您需要释放BarCodeDetector。在致电barcodeDetector.release()
之前使用Runnable