Demo of Android QR Scanner App
We hope you have installed Android Studio. If you haven’t then follow the tutorial Installing Android Studio. and then return here. Also before going through this tutorial we suggest you make a simple Hello World App and run it on your smartphone. You can learn How to Connect, Configure App on Real Android device and Run Hello World program with Android Studio . So now let’s create our Led Flash Light Application. Start by creating a new project in Android Studio as follows.
Create a new Android Studio project
Please follow the steps:
- Open Android Studio and create a new project by going to File => New => New Project. Enter the Application Name as QrCodeScanner and your company domain name. (We have used our company domain i.e androidtutorialpoint.com. Similarly you can use yours).
- Click Next and choose Minimum SDK. We have kept the default setting and click Next.
- Choose Empty Activity and click next.
- In the next screen enter Activity Name as QrCodeScannerActivity and remember to check the Generate Layout Button and then click Finish.
Gradle will sync the project and resolve all the dependencies.
Adding Permissions and Dependencies for android QR code scanner app
Open your AndroidManifest.xml file and add the following permissions.
<uses-permission android:name="android.permission.CAMERA"/> <uses-feature android:name="android.hardware.camera"/> <uses-feature android:name="android.hardware.camera.autofocus"/>
These uses-permissions tag tells the Android OS that our app will require access to CAMERA. Similarly uses-feature tells what features will be used in the app.
Open your App’s build.gradle file and add the following dependency.
compile 'me.dm7.barcodescanner:zxing:1.9'
Adding Functionality to Scan QR Code and Bar Code
Open QrCodeScannerActivity.java and declare the following imports variables. Please note that our activity implements the Interface ZXingScannerView.ResultHandler to be able to act as QR Code Scanner as well as Bar Code scanner.
QrCodeScannerActivity.java
package com.androidtutorialpoint.qrcodescanner; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Toast; import com.google.zxing.Result; import me.dm7.barcodescanner.zxing.ZXingScannerView; import static android.Manifest.permission.CAMERA; public class QrCodeScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler { private static final int REQUEST_CAMERA = 1; private ZXingScannerView mScannerView;
The constant REQUEST_CAMERA is used while getting the permissions from the user to use the camera. ZXingScannerView provides the view to scan the QR code and Bar code as shown below.
Next, in the onCreate() method add the following code.
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.e("onCreate", "onCreate"); mScannerView = new ZXingScannerView(this); setContentView(mScannerView); int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= android.os.Build.VERSION_CODES.M) { if (checkPermission()) { Toast.makeText(getApplicationContext(), "Permission already granted", Toast.LENGTH_LONG).show(); } else { requestPermission(); } } }
We create a new ZXingScannerView by passing the context. Then set the conteent view to the same using the setContentView() method. To access the Camera, we need permissions.
Starting from Android 6.0( Android Marshmallow) we have to get the user permissions at the runtime. So the next few lines checks for the api version
We need to detect whether the app has the required permissions or not otherwise we need to request those from the user befor accessing the camera.
Add the following code which implements the requestPermission() and checkPermission() methods for the android QR Code Scanner app.
private boolean checkPermission() { return ( ContextCompat.checkSelfPermission(getApplicationContext(), CAMERA ) == PackageManager.PERMISSION_GRANTED); } private void requestPermission() { ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA); } public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_CAMERA: if (grantResults.length > 0) { boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED; if (cameraAccepted){ Toast.makeText(getApplicationContext(), "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show(); }else { Toast.makeText(getApplicationContext(), "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (shouldShowRequestPermissionRationale(CAMERA)) { showMessageOKCancel("You need to allow access to both the permissions", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[]{CAMERA}, REQUEST_CAMERA); } } }); return; } } } } break; } } private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) { new android.support.v7.app.AlertDialog.Builder(QrCodeScannerActivity.this) .setMessage(message) .setPositiveButton("OK", okListener) .setNegativeButton("Cancel", null) .create() .show(); }
For the first time, when the user installs the app, the app will request permission to use the Camera, on subsequent app runs we don’t need to provide any permission.
@Override public void onResume() { super.onResume(); int currentapiVersion = android.os.Build.VERSION.SDK_INT; if (currentapiVersion >= android.os.Build.VERSION_CODES.M) { if (checkPermission()) { if(mScannerView == null) { mScannerView = new ZXingScannerView(this); setContentView(mScannerView); } mScannerView.setResultHandler(this); mScannerView.startCamera(); } else { requestPermission(); } } } @Override public void onDestroy() { super.onDestroy(); mScannerView.stopCamera(); }
We need to handle the onResume() and onDestroy() lifecycle methods for QRCodeScannerActivity. In the onResume() we check if the ScannerView is null or not, in case it is null we create a new one and then start the Camera to capture the QR Code using the startCamera() method. Similarly in the onDestroy() we release the Camera using the stopCamera().
To implement the ZXingScannerView.ResultHandler we need to implement the method handleResult(). This method contains the Logic to handle the Result of the scan from the android QR Scanner or the Bar Code scanner. Add the following code that will handle the result for you.
@Override public void handleResult(Result rawResult) { final String result = rawResult.getText(); Log.d("QRCodeScanner", rawResult.getText()); Log.d("QRCodeScanner", rawResult.getBarcodeFormat().toString()); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Scan Result"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { mScannerView.resumeCameraPreview(QrCodeScannerActivity.this); } }); builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(result)); startActivity(browserIntent); } }); builder.setMessage(rawResult.getText()); AlertDialog alert1 = builder.create(); alert1.show(); }
On getting the result from the QR Code or Bar Code scan, this method will be called. We are logging the result to the LogCat as well as Showing a AlertDialog with the result of the scan and two buttons. Clicking on OK button will resume the Scanning. If you scanned the QR code for some website then you can open that website by clicking on the Visit button.
Now run your newly created Android QR Scanner app on an Actual Device, Point to a QR Code or a Bar Code and you will be amazed to see the result. You can downlaod the android QR Scanner app source code by clicking on the Download Now button.
What’s Next ??
We will soon cover more tutorials under Learn By Doing !! section to provide hand’s on experience. Thanks guys for reading. If you have any doubts or suggestion then please leave comments in the comments section below . Subscribe to our website for latest Android Tutorials. Also do Like our Facebook Page or Add us on Twitter.
This is the most complete tutorial about zxing function.
Thanks!
not working. the mScannerView is not executing at all.
Make sure that you have added the following in the library dependency in your app’s build.gradle file
‘me.dm7.barcodescanner:zxing:1.9’
nothing show when run???????
It doesn’t build. I followed the tutorial and the I just gave them my email address to download the project. It doesn’t build either. Moving on.
really nice tutorial,
I want to ask how to open in webView instead of browser?