Use to Scan the QR code on an Android phone (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional barcode).
- QR codes often contain data for a locator, identifier, or tracker that points to a website or application. This means we can scan multiple barcodes, QR Codes, and faces together. Be it with Scan the QR code on an Android phone is video, a picture, or a video stream. But covering all of this in a single article is not possible.
- It uses four standardized encoding modes (numeric, alphanumeric, byte/binary, and kanji) to store data efficiently; extensions may also be used. It consists of black squares arranged in a square grid on a white background, which can be read by an imaging device such as a camera.
You can find out more about the Flutter app development services page.
At the very first, We have to add the Google Play Services Integration in our app and add the GMS services dependency in build.gradle
1 2 3 |
dependencies { compile 'com.google.android.gms:play-services-vision:11.4.0' } |
And at the global build.gradle must have
1 2 3 4 5 6 7 8 |
allprojects { repositories { jcenter() maven { url "https://maven.google.com" } } } |
Before installation, Scan the QR Code to make Mobile Vision APIs functional and add the metadata tag inside the Manifest file
1 2 3 |
<meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="barcode"/> |
Also, add the uses permission and uses feature inside the Manifest file
1 2 3 4 5 |
<uses-feature android:name="android.hardware.camera" android:required="true"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> |
Now, Make the xml file for show the QR scan code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".barcbarode.BarCodeActivity"> <ImageView android:id="@+id/img_launcher" android:layout_width="150dp" android:layout_height="150dp" android:layout_marginTop="100dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" android:src="@mipmap/ic_launcher_round"/> <TextView android:id="@+id/text_scanner_result" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/img_launcher" android:text="Scanner Results:" android:textStyle="bold"/> <TextView android:id="@+id/text_scan_value" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/text_scanner_result" android:layout_marginTop="10dp"/> <Button android:id="@+id/button_scan" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginBottom="80dp" android:layout_marginTop="20dp" android:text="Scan"/> </androidx.constraintlayout.widget.ConstraintLayout> |
Now, the BarCodeActivity code is given below:
For more understanding please go through these links:
https://mobikul.com/swift-qr-code-scanner-generator/
https://mobikul.com/swift-qr-code-scanner-generator/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 |
class BarCodeActivity : AppCompatActivity() { private val LOG_TAG = "Barcode Scanning" private val PHOTO_REQUEST = 10 private var detector: BarcodeDetector? = null private var imageUri: Uri? = null private val REQUEST_WRITE_PERMISSION = 20 private val SAVED_INSTANCE_URI = "uri" private val SAVED_INSTANCE_RESULT = "result" var activityBarCodeBinding: ActivityBarCodeBinding?=null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activityBarCodeBinding = DataBindingUtil.setContentView(this,R.layout.activity_bar_code) setBarCode(savedInstanceState) } private fun setBarCode(savedInstanceState: Bundle?){ if (savedInstanceState != null) { imageUri = Uri.parse(savedInstanceState.getString(SAVED_INSTANCE_URI)) activityBarCodeBinding?.textScannerResult?.text = savedInstanceState.getString(SAVED_INSTANCE_RESULT) } activityBarCodeBinding?.buttonScan?.setOnClickListener({ ActivityCompat.requestPermissions( applicationContext as Activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_WRITE_PERMISSION ) }) detector = BarcodeDetector.Builder(applicationContext) .setBarcodeFormats(Barcode.DATA_MATRIX or Barcode.QR_CODE) .build() if (!detector!!.isOperational) { activityBarCodeBinding?.textScannerResult?.text = "Could not set up the detector!" return } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String?>, grantResults: IntArray ) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) when (requestCode) { REQUEST_WRITE_PERMISSION -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { takePicture() } else { Toast.makeText(this@BarCodeActivity, "Permission Denied!", Toast.LENGTH_SHORT).show() } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == PHOTO_REQUEST && resultCode == RESULT_OK) { launchMediaScanIntent() try { val bitmap = decodeBitmapUri(this, imageUri!!) if (detector!!.isOperational && bitmap != null) { val frame: Frame = Frame.Builder().setBitmap(bitmap).build() val barcodes = detector!!.detect(frame) for (index in 0 until barcodes.size()) { val code = barcodes.valueAt(index) activityBarCodeBinding?.textScannerResult?.text = activityBarCodeBinding?.textScannerResult?.text.toString() + code.displayValue + "\n" //Required only if you need to extract the type of barcode val type = barcodes.valueAt(index).valueFormat when (type) { Barcode.CONTACT_INFO -> Log.i(LOG_TAG, code.contactInfo.title) Barcode.EMAIL -> Log.i(LOG_TAG, code.email.address) Barcode.ISBN -> Log.i(LOG_TAG, code.rawValue) Barcode.PHONE -> Log.i(LOG_TAG, code.phone.number) Barcode.PRODUCT -> Log.i(LOG_TAG, code.rawValue) Barcode.SMS -> Log.i(LOG_TAG, code.sms.message) Barcode.TEXT -> Log.i(LOG_TAG, code.rawValue) Barcode.URL -> Log.i(LOG_TAG, "url: " + code.url.url) Barcode.WIFI -> Log.i(LOG_TAG, code.wifi.ssid) Barcode.GEO -> Log.i( LOG_TAG, code.geoPoint.lat.toString() + ":" + code.geoPoint.lng ) Barcode.CALENDAR_EVENT -> Log.i(LOG_TAG, code.calendarEvent.description) Barcode.DRIVER_LICENSE -> Log.i( LOG_TAG, code.driverLicense.licenseNumber ) else -> Log.i(LOG_TAG, code.rawValue) } } if (barcodes.size() == 0) { activityBarCodeBinding?.textScannerResult?.text = "Scan Failed: Found nothing to scan" } } else { activityBarCodeBinding?.textScannerResult?.text = "Could not set up the detector!" } } catch (e: Exception) { Toast.makeText(this, "Failed to load Image", Toast.LENGTH_SHORT) .show() Log.e(LOG_TAG, e.toString()) } } } private fun takePicture() { val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE) val photo = File(Environment.getExternalStorageDirectory(), "picture.jpg") imageUri = FileProvider.getUriForFile( this@BarCodeActivity, BuildConfig.APPLICATION_ID.toString() + ".provider", photo ) intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri) startActivityForResult(intent, PHOTO_REQUEST) } override fun onSaveInstanceState(outState: Bundle) { if (imageUri != null) { outState.putString(SAVED_INSTANCE_URI, imageUri.toString()) outState.putString(SAVED_INSTANCE_RESULT, activityBarCodeBinding?.textScannerResult?.text.toString()) } super.onSaveInstanceState(outState) } private fun launchMediaScanIntent() { val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE) mediaScanIntent.data = imageUri this.sendBroadcast(mediaScanIntent) } @Throws(FileNotFoundException::class) private fun decodeBitmapUri(ctx: Context, uri: Uri): Bitmap? { val targetW = 600 val targetH = 600 val bmOptions = BitmapFactory.Options() bmOptions.inJustDecodeBounds = true BitmapFactory.decodeStream(ctx.getContentResolver().openInputStream(uri), null, bmOptions) val photoW = bmOptions.outWidth val photoH = bmOptions.outHeight val scaleFactor = Math.min(photoW / targetW, photoH / targetH) bmOptions.inJustDecodeBounds = false bmOptions.inSampleSize = scaleFactor return BitmapFactory.decodeStream( ctx.getContentResolver() .openInputStream(uri), null, bmOptions ) } } |
You can also check this link: https://developers.google.com/vision/android/barcodes-overview
Conclusion:
In this post, you learned that it shows the bar code text after scanning the bar code using the Mobile Vision APIs. It reads the data, as well as understands what type of data it is.