When a requirement in your app to scan bar codes and QR codes, in this tutorial we will see how to scanning bar codes and QR codes. Here I am using Zxing and Zbar open source libraries. you can choose any one of the library.
Screen Shots:
Download Source Code
Step 1: Build Gradle
To start this application we need to include Zxing and Zbar dependencies in our build.gradle file.Check the below my build.gradle file.
build.gradle:
apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "com.prasad.zxingscannerex" minSdkVersion 15 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.1.0' compile 'com.android.support.constraint:constraint-layout:1.0.0-beta4' testCompile 'junit:junit:4.12' compile 'me.dm7.barcodescanner:zxing:1.9' compile 'me.dm7.barcodescanner:zbar:1.9' }
Step 2: XML Layouts
Open activity_main.xml file and do the below changes.
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_margin="10dp" android:orientation="vertical"> <Button android:id="@+id/btn_scanner" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Zxing Scanner" android:textAllCaps="false" /> <Button android:id="@+id/btn_zbar_scanner" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Zbar Scanner" android:textAllCaps="false" /> </LinearLayout> </RelativeLayout>
Create a new layout resource name as activity_zxing_scanner.xml and modify below changes.
activity_zxing_scanner.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff"> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
Create a new layout resource name as activity_zbar_scanner.xml and modify below changes.
activity_zbar_scanner.xml:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffffff"> <FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
Step 3: Java Classes
Open MainActivity.java class and do the below changes.
MainActivity.java:
package com.prasad.zxingscannerex; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button scannerBtn = (Button) findViewById(R.id.btn_scanner); Button zbarScannerBtn = (Button) findViewById(R.id.btn_zbar_scanner); scannerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ZxingScannerActivity.class); startActivity(intent); } }); zbarScannerBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(v.getContext(), ZbarScannerActivity.class); startActivity(intent); } }); } }
Create a new Activity java class name as ZxingScannerActivity.java and modify below changes.
ZxingScannerActivity.java:
package com.prasad.zxingscannerex; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import android.widget.Toast; import com.google.zxing.Result; import me.dm7.barcodescanner.zxing.ZXingScannerView; public class ZxingScannerActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler { private ZXingScannerView mScannerView; static final Integer CAMERA = 0x1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_zxing_scanner); ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame); mScannerView = new ZXingScannerView(this); contentFrame.addView(mScannerView); askForPermission(Manifest.permission.CAMERA, CAMERA); } private void askForPermission(String permission, Integer requestCode) { if (ContextCompat.checkSelfPermission(ZxingScannerActivity.this, permission) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(ZxingScannerActivity.this, permission)) { //This is called if user has denied the permission before //In this case I am just asking the permission again ActivityCompat.requestPermissions(ZxingScannerActivity.this, new String[]{permission}, requestCode); } else { ActivityCompat.requestPermissions(ZxingScannerActivity.this, new String[]{permission}, requestCode); } } else { // Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show(); mScannerView.setResultHandler(this); mScannerView.startCamera(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED) { switch (requestCode) { //Camera case 1: mScannerView.setResultHandler(this); mScannerView.startCamera(); break; } Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show(); } } @Override public void onPause() { super.onPause(); mScannerView.stopCamera(); } @Override public void handleResult(Result result) { Toast.makeText(this, "Contents = " + result.getText() + ", Format = " + result.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show(); // * Wait 3 seconds to resume the preview. Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mScannerView.resumeCameraPreview(ZxingScannerActivity.this); } }, 3000); } }
Create a new Activity java class name as ZbarScannerActivity.java and modify below changes.
ZbarScannerActivity.java:
package com.prasad.zxingscannerex; import android.Manifest; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.view.ViewGroup; import android.widget.Toast; import me.dm7.barcodescanner.zbar.Result; import me.dm7.barcodescanner.zbar.ZBarScannerView; public class ZbarScannerActivity extends AppCompatActivity implements ZBarScannerView.ResultHandler { private ZBarScannerView mScannerView; static final Integer CAMERA = 0x1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_zbar_scanner); ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame); mScannerView = new ZBarScannerView(this); contentFrame.addView(mScannerView); askForPermission(Manifest.permission.CAMERA, CAMERA); } private void askForPermission(String permission, Integer requestCode) { if (ContextCompat.checkSelfPermission(ZbarScannerActivity.this, permission) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(ZbarScannerActivity.this, permission)) { //This is called if user has denied the permission before //In this case I am just asking the permission again ActivityCompat.requestPermissions(ZbarScannerActivity.this, new String[]{permission}, requestCode); } else { ActivityCompat.requestPermissions(ZbarScannerActivity.this, new String[]{permission}, requestCode); } } else { // Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show(); mScannerView.setResultHandler(this); mScannerView.startCamera(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED) { switch (requestCode) { //Camera case 1: mScannerView.setResultHandler(this); mScannerView.startCamera(); break; } Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show(); } } @Override public void onPause() { super.onPause(); mScannerView.stopCamera(); } @Override public void handleResult(Result result) { Toast.makeText(this, "Contents = " + result.getContents() + ", Format = " + result.getBarcodeFormat().getName(), Toast.LENGTH_SHORT).show(); // * Wait 3 seconds to resume the preview. Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mScannerView.resumeCameraPreview(ZbarScannerActivity.this); } }, 3000); } }
4. Android Manifest
Open AndroidManifest.xml add the Camera permission and declare activity classes.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.prasad.zxingscannerex"> <uses-permission android:name="android.permission.CAMERA" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".ZxingScannerActivity" /> <activity android:name=".ZbarScannerActivity"></activity> </application> </manifest>
5. Reference:
Credits goes to this GitHub link.