I'm new to Android development and currently working on an app which lets the user scan the QR code using either camera or choosing a picture from Gallery using Barcode scanning kit. The app works completely fine for Android 9 (Api level 28) and above. The app works fine for all versions while scanning using camera. But for android 8 and below, I'm unable to scan any QR code if I choose a picture from gallery. I searched everywhere but didn't find any solution.
Here's the code I tried: -
mChoosePhoto = registerForActivityResult(new ActivityResultContracts.GetContent(), result -> {
InputImage image;
BarcodeScannerOptions options =
new BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_QR_CODE)
.build();
BarcodeScanner scanner = BarcodeScanning.getClient(options);
Log.v("myUri", String.valueOf(result));
try {
image = InputImage.fromFilePath(this, result);
scanner.process(image)
.addOnSuccessListener(MainActivity.this::processResult)
.addOnFailureListener(e -> {
// Task failed with an exception
Toast.makeText(MainActivity.this, "Failed to scan.", Toast.LENGTH_SHORT).show();
e.printStackTrace();
});
} catch (IOException e) {
e.printStackTrace();
}
});
And then in processResult() Method
private void processResult(List<Barcode> barcodes){
for (Barcode barcode: barcodes) {
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(100);
// Rect bounds = barcode.getBoundingBox();
// Point[] corners = barcode.getCornerPoints();
//
// String rawValue = barcode.getRawValue();
int valueType = barcode.getValueType();
switch (valueType) {
case Barcode.TYPE_WIFI:
String ssid = barcode.getWifi().getSsid();
String password = barcode.getWifi().getPassword();
int type = barcode.getWifi().getEncryptionType();
break;
case Barcode.TYPE_URL:
String title = barcode.getUrl().getTitle();
String url = barcode.getUrl().getUrl();
Toast.makeText(this, title + " " + url, Toast.LENGTH_SHORT).show();
break;
case Barcode.TYPE_TEXT:
String text = barcode.getDisplayValue();
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}
}