'Android force BarCode scanner to scan only BarCodes
I have an Android app, where it simply scans the Barcode and this is working fine.
The problem is, sometimes if I have my phone during scanning turned to carpet in my room, or even a PC keyboard, it scans it and shows random numbers. The app thinks that it is some kind of Barcode and throws a random number.
The code works perfectly with Barcodes, but it scans also some other surfaces randomly (not always, but happens quite often).
Part of my code:
private void initialiseDetectorsAndSources() {
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.EAN_8 | Barcode.EAN_13)
.build();
cameraSource = new CameraSource.Builder(this, barcodeDetector)
.setRequestedPreviewSize(1920, 1080)
.setAutoFocusEnabled(true)
.build();
surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(AddOsivo.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
cameraSource.start(surfaceView.getHolder());
} else {
ActivityCompat.requestPermissions(AddOsivo.this, new
String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
}
} 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(@NonNull Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
barcodeText.post(() -> {
barcodeData = barcodes.valueAt(0).displayValue;
barcodeText.setText(barcodeData);
toneGen1.startTone(ToneGenerator.TONE_CDMA_ONE_MIN_BEEP, 150);
cameraSource.stop();
EditText ean = findViewById(R.id.barcode_text);
String eantext = ean.getText().toString();
});
}
}
});
}
As you can see, I tried to use setBarcodeFormats(Barcode.EAN_8 | Barcode.EAN_13)
which should limit the scanner to all Barcode types only, so I am not sure, why it thinks, that my keyboard or carpet is a barcode :)
Using this detector library:
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
Any suggestions?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|