There are many applications that uses Barcode scanner in one or the other way and its not that difficult to create one for yourself but when scanning a Barcode is a small part of your application then creating a scanner by yourself is not a worthy decision. I came across the same situation when I need a good Barcode library to add in my application. After using a handful of options including Google vision API, I finally came across the one that solved each an every problem of mine.
The library used is a third party library so please go through the license policy before use. The GitHub link to the library is here.
This blog is written in Java Language.
The procedure to use is extremely easy. Just add this dependency to your application build.gradle file
1 |
compile 'com.tarun0.zxing-standalone:zxing-standalone:1.0.0' |
Now wherever you need to access the Barcode just add the below lines of code
1 2 3 4 |
Intent intent = new Intent(getApplicationContext(), CaptureActivity.class); intent.setAction("com.google.zxing.client.android.SCAN"); intent.putExtra("SAVE_HISTORY", false); startActivityForResult(intent, RC_BARCODE_CAPTURE); |
As a Barcode is scanned the result will be redirected back to this activity where you can get the scanned Barcode result as
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == RC_BARCODE_CAPTURE) { if (resultCode == RESULT_OK) { if (data.getStringExtra("SCAN_RESULT_FORMAT").equals("UPC_A") || data.getStringExtra("SCAN_RESULT_FORMAT").equals("UPC_E")) { String contents = data.getStringExtra("SCAN_RESULT"); mBinding.productUpc.setText(contents); } else { Toast.makeText(this, "The barcode scanned should be of type UPC", Toast.LENGTH_LONG).show(); } } else if (resultCode == RESULT_CANCELED) { Log.d("TAG", "RESULT_CANCELED"); Toast.makeText(this, "Scanning cancelled", Toast.LENGTH_LONG).show(); } } } |
I needed only UPC_A and UPC_E code so I had the result checked but you can use it as you want.
NOTE : 1) Make sure that you declare RC_BARCODE_CAPTURE before in your Activity or Fragment before adding the intent to launch else you will get compilation errors.
OR
Replace RC_BARCODE_CAPTURE with your own request code.
2) The result barcode is shown in the string named contents, feel free to use it as per your need.
Check out a classic example of barcode search functionality provided by Mobikul over – https://mobikul.com/features/barcode-product-search/