Android Machine Learning Code Scanner
For this article we will see and explain an easy implementation for the code scanner (QR code, barcode etc.) that using machine learning provides by Google with few lines of code. The only pre-request is the Google Play Service installed on the device. You don’t need to request permission for the camera because its coming directly from the Google Play Services that the permission is already granted. To achieve this we will follow only three steps.
First of all, we need to add the following dependency into the application Gradle file.
Groovy:
implementation 'com.google.android.gms:play-services-code-scanner:16.1.0'
Kotlin:
implementation("com.google.android.gms:play-services-code-scanner:16.1.0")
Second, we need to add inside the application manifest the follow meta-data, be able to download the scanner from the Google Play Services.
<application ...>
...
<meta-data
android:name="com.google.mlkit.vision.DEPENDENCIES"
android:value="barcode_ui"/>
...
</application>
Third and last step, you need to initialize the GmsBarcodeScannerOptions Builder that set the barcode formats (example: Barcode.FORMAT_CODE_128, Barcode.FORMAT_CODE_39. Barcode.FORMAT_CODE_93 — there are more than ten barcode formats, you can check them in the following link and select a correct one for your implementation). After, get an instance from the GmsBarcodeScanning.getClient(context, <”GmsBarcodeScannerOptions”>) and override the three listeners.
- addOnSuccessListener: This is the success call back and return the data from the scanning.
- addOnFailureListener: This is the failure call back and get the error.
- addOnCanceledListener: This is the cancelled call back.
private fun bacCodeProcess(
context: Context,
success: (String) -> Unit,
canceled: () -> Unit,
failed: (Exception) -> Unit
) {
GmsBarcodeScannerOptions.Builder()
.setBarcodeFormats(
Barcode.FORMAT_QR_CODE,
Barcode.FORMAT_CODE_128,
)
.build().apply {
GmsBarcodeScanning.getClient(context, this).apply {
startScan()
.addOnSuccessListener { barcode ->
val displayValue: String? = barcode.displayValue
if (displayValue != null) {
success(displayValue)
}
//Log.d("callBack", displayValue.toString())
}
.addOnCanceledListener {
canceled()
//Log.d("callBack", "Canceled")
}
.addOnFailureListener { e ->
failed(e)
//Log.d("callBack", e.message.toString())
}
}
}
}
Check my sample project in my GitHub account to the follow link for more information:
I hope you find the article and sample project useful. Let me know your opinion under the comments, feel free to report any issue. I will appreciate it if you let a clap, so, if I have your support to continue writing.
References: