Skip to main content

How to create qr code and barcode reader app for android phone?


For qr code and barcode reader app for android phone, At some point of the development of Android application, occasionally it is required to provide a functionality that scans a QR code or barcode. Scanning the QR code can be achieved programmatically by means of the usage of many approaches:

  • the usage of an internet-based API, where the QR code or barcode is uploaded to the server, and the server returns the results.
  • the usage of an internet-based totally utility that accesses your camera and scans the QR code or barcode and returns the results.
  • by means of Integrating the Mobile Vision API of Google Play Service.
Here we are going to share the world how to create qr code or barcode reader app for android phone with certain steps.


QR Code Scanner Example

In this example, we will scan the QR code of a web URL and Email address, and act on it. Here we will use the Mobile Vision API of Google Play Service to scan the QR code. The Mobile Vision API supports the following formats of the barcode.
  • 1D barcodes: EAN-8, UPC-A, EAN-13, EAN-8, UPC-E, Code-93, Code-128, Code-39, Codabar, ITF.
  • 2D barcodes: QR Code, Data Matrix, AZTEC, PDF-417.
Create an activity_main.xml and add the following code.


  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context="example.com.qrcodebarcodescanner.MainActivity">  
  8.   
  9.     <Button  
  10.         android:id="@+id/btnScanBarcode"  
  11.         android:layout_width="300dp"  
  12.         android:layout_height="wrap_content"  
  13.         android:layout_centerHorizontal="true"  
  14.         android:layout_marginBottom="44dp"  
  15.         android:layout_marginEnd="8dp"  
  16.         android:layout_marginStart="8dp"  
  17.         android:text="@string/scan_barcode"  
  18.         app:layout_constraintBottom_toBottomOf="parent"  
  19.         app:layout_constraintEnd_toEndOf="parent"  
  20.         app:layout_constraintHorizontal_bias="0.676"  
  21.         app:layout_constraintStart_toStartOf="parent" />  
  22.   
  23. </android.support.constraint.ConstraintLayout>  

Create an activity_scanned_barcode.xml layout and add the following code. The SurfaceView widget is used for camera source.

activity_scanned_barcode.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:tools="http://schemas.android.com/tools"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent"  
  6.     android:padding="@dimen/activity_horizontal_margin">  
  7.   
  8.     <SurfaceView  
  9.         android:id="@+id/surfaceView"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="match_parent"  
  12.         android:layout_above="@+id/btnAction"  
  13.         android:layout_alignParentLeft="true"  
  14.         android:layout_alignParentStart="true"  
  15.         android:layout_centerVertical="true" />  
  16.   
  17.     <TextView  
  18.         android:id="@+id/txtBarcodeValue"  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:layout_alignParentTop="true"  
  22.         android:layout_marginLeft="@dimen/activity_horizontal_margin"  
  23.         android:layout_marginStart="@dimen/activity_horizontal_margin"  
  24.         android:text="No Barcode Detected"  
  25.         android:textColor="@android:color/white"  
  26.         android:textSize="20sp" />  
  27.   
  28.   
  29.     <Button  
  30.         android:id="@+id/btnAction"  
  31.         android:layout_width="match_parent"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_alignParentBottom="true"  
  34.         android:text="ADD CONTENT IN THE MAIL" />  
  35. </RelativeLayout>  

Create an activity_email.xml layout to perform email action.

activity_email.xml

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:layout_height="match_parent"  
  7.     tools:context="example.com.qrcodebarcodescanner.EmailActivity">  
  8.   
  9.     <Button  
  10.         android:id="@+id/btnSendEmail"  
  11.         android:layout_width="300dp"  
  12.         android:layout_height="wrap_content"  
  13.         android:layout_below="@+id/inBody"  
  14.         android:layout_centerHorizontal="true"  
  15.         android:layout_marginBottom="64dp"  
  16.         android:layout_marginEnd="8dp"  
  17.         android:layout_marginStart="8dp"  
  18.         android:text="@string/send_email"  
  19.         app:layout_constraintBottom_toBottomOf="parent"  
  20.         app:layout_constraintEnd_toEndOf="parent"  
  21.         app:layout_constraintStart_toStartOf="parent" />  
  22.   
  23.   
  24.     <TextView  
  25.         android:id="@+id/txtEmailAddress"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="wrap_content"  
  28.         android:layout_alignParentTop="true"  
  29.         android:layout_marginBottom="8dp"  
  30.         android:layout_marginEnd="8dp"  
  31.         android:layout_marginStart="8dp"  
  32.         android:layout_marginTop="8dp"  
  33.         android:text="Email Address: "  
  34.         android:textSize="16dp"  
  35.         android:textStyle="bold"  
  36.         app:layout_constraintBottom_toTopOf="@+id/inSubject"  
  37.         app:layout_constraintEnd_toEndOf="parent"  
  38.         app:layout_constraintStart_toStartOf="parent"  
  39.         app:layout_constraintTop_toTopOf="parent" />  
  40.   
  41.     <EditText  
  42.         android:id="@+id/inSubject"  
  43.         android:layout_width="match_parent"  
  44.         android:layout_height="wrap_content"  
  45.         android:layout_below="@+id/txtEmailAddress"  
  46.         android:layout_centerHorizontal="true"  
  47.         android:layout_marginEnd="8dp"  
  48.         android:layout_marginStart="8dp"  
  49.         android:layout_marginTop="88dp"  
  50.         android:ems="10"  
  51.         android:hint="Subject"  
  52.         app:layout_constraintEnd_toEndOf="parent"  
  53.         app:layout_constraintStart_toStartOf="parent"  
  54.         app:layout_constraintTop_toTopOf="parent" />  
  55.   
  56.     <EditText  
  57.         android:id="@+id/inBody"  
  58.         android:layout_width="match_parent"  
  59.         android:layout_height="wrap_content"  
  60.         android:layout_below="@+id/inSubject"  
  61.         android:layout_centerHorizontal="true"  
  62.         android:layout_marginEnd="8dp"  
  63.         android:layout_marginStart="8dp"  
  64.         android:layout_marginTop="164dp"  
  65.         android:ems="10"  
  66.         android:hint="Body"  
  67.         app:layout_constraintEnd_toEndOf="parent"  
  68.         app:layout_constraintHorizontal_bias="1.0"  
  69.         app:layout_constraintStart_toStartOf="parent"  
  70.         app:layout_constraintTop_toTopOf="parent" />  
  71. </android.support.constraint.ConstraintLayout>  

Add the Google Mobile Vision API in build.gradle file.

build.gradle

  1. implementation of 'com.google.android.gms:play-services-vision:11.8.0'  

In the MainActivity.java file, add the following code. By clicking the button btnScanBarcode it call the ScannedBarcodeActivity.java class.

MainActivity.java

  1. package example.com.qrcodebarcodescanner;  
  2.   
  3. import android.content.Intent;  
  4. import android.support.v7.app.AppCompatActivity;  
  5. import android.os.Bundle;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8.   
  9. public class MainActivity extends AppCompatActivity {  
  10.     Button  btnScanBarcode;  
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.activity_main);  
  15.         btnScanBarcode = findViewById(R.id.btnScanBarcode);  
  16.   
  17.         btnScanBarcode.setOnClickListener(new View.OnClickListener() {  
  18.             @Override  
  19.             public void onClick(View view) {  
  20.                 startActivity(new Intent(MainActivity.this, ScannedBarcodeActivity.class));  
  21.             }  
  22.         });  
  23.     }  
  24. }  

In the ScannedBarcodeActivity.java activity class, add the following code. This class scans the QR code through the camera. In this class, we will generate two QR code, one for web URL and another is for an email address. A QR code can be generated from any of QR code generator website.

ScannedBarcodeActivity.java

  1. package example.com.qrcodebarcodescanner;  
  2.   
  3. import android.Manifest;  
  4. import android.content.Intent;  
  5. import android.content.pm.PackageManager;  
  6. import android.net.Uri;  
  7. import android.os.Bundle;  
  8. import android.support.v4.app.ActivityCompat;  
  9. import android.support.v7.app.AppCompatActivity;  
  10. import android.util.SparseArray;  
  11. import android.view.SurfaceHolder;  
  12. import android.view.SurfaceView;  
  13. import android.view.View;  
  14. import android.widget.Button;  
  15. import android.widget.TextView;  
  16. import android.widget.Toast;  
  17. import com.google.android.gms.vision.CameraSource;  
  18. import com.google.android.gms.vision.Detector;  
  19. import com.google.android.gms.vision.barcode.Barcode;  
  20. import com.google.android.gms.vision.barcode.BarcodeDetector;  
  21. import java.io.IOException;  
  22.   
  23. public class ScannedBarcodeActivity extends AppCompatActivity {  
  24.   
  25.   
  26.     SurfaceView surfaceView;  
  27.     TextView txtBarcodeValue;  
  28.     private BarcodeDetector barcodeDetector;  
  29.     private CameraSource cameraSource;  
  30.     private static final int REQUEST_CAMERA_PERMISSION = 201;  
  31.     Button btnAction;  
  32.     String intentData = "";  
  33.     boolean isEmail = false;  
  34.   
  35.     @Override  
  36.     protected void onCreate(Bundle savedInstanceState) {  
  37.         super.onCreate(savedInstanceState);  
  38.         setContentView(R.layout.activity_scanned_barcode);  
  39.         initViews();  
  40.     }  
  41.   
  42.     private void initViews() {  
  43.         txtBarcodeValue = findViewById(R.id.txtBarcodeValue);  
  44.         surfaceView = findViewById(R.id.surfaceView);  
  45.         btnAction = findViewById(R.id.btnAction);  
  46.         btnAction.setOnClickListener(new View.OnClickListener() {  
  47.             @Override  
  48.             public void onClick(View v) {  
  49.                 if (intentData.length() > 0) {  
  50.                     if (isEmail)  
  51.                         startActivity(new Intent(ScannedBarcodeActivity.this, EmailActivity.class).putExtra("email_address", intentData));  
  52.                     else {  
  53.                         startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(intentData)));  
  54.                     }  
  55.                 }  
  56.             }  
  57.         });  
  58.     }  
  59.   
  60.     private void initialiseDetectorsAndSources() {  
  61.   
  62.         Toast.makeText(getApplicationContext(), "Barcode scanner started", Toast.LENGTH_SHORT).show();  
  63.         barcodeDetector = new BarcodeDetector.Builder(this)  
  64.                 .setBarcodeFormats(Barcode.ALL_FORMATS)  
  65.                 .build();  
  66.   
  67.         cameraSource = new CameraSource.Builder(this, barcodeDetector)  
  68.                 .setRequestedPreviewSize(19201080)  
  69.                 .setAutoFocusEnabled(true//you should add this feature  
  70.                 .build();  
  71.   
  72.         surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {  
  73.             @Override  
  74.             public void surfaceCreated(SurfaceHolder holder) {  
  75.                 try {  
  76.                     if (ActivityCompat.checkSelfPermission(ScannedBarcodeActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {  
  77.                         cameraSource.start(surfaceView.getHolder());  
  78.                     } else {  
  79.                         ActivityCompat.requestPermissions(ScannedBarcodeActivity.thisnew  
  80.                                 String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);  
  81.                     }  
  82.   
  83.                 } catch (IOException e) {  
  84.                     e.printStackTrace();  
  85.                 }  
  86.             }  
  87.   
  88.             @Override  
  89.             public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {  
  90.             }  
  91.   
  92.             @Override  
  93.             public void surfaceDestroyed(SurfaceHolder holder) {  
  94.                 cameraSource.stop();  
  95.             }  
  96.         });  
  97.   
  98.   
  99.         barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {  
  100.             @Override  
  101.             public void release() {  
  102.                 Toast.makeText(getApplicationContext(), "To prevent memory leaks barcode scanner has been stopped", Toast.LENGTH_SHORT).show();  
  103.             }  
  104.   
  105.             @Override  
  106.             public void receiveDetections(Detector.Detections<Barcode> detections) {  
  107.                 final SparseArray<Barcode> barcodes = detections.getDetectedItems();  
  108.                 if (barcodes.size() != 0) {  
  109.                     txtBarcodeValue.post(new Runnable() {  
  110.                         @Override  
  111.                         public void run() {  
  112.   
  113.                             if (barcodes.valueAt(0).email != null) {  
  114.                                 txtBarcodeValue.removeCallbacks(null);  
  115.                                 intentData = barcodes.valueAt(0).email.address;  
  116.                                 txtBarcodeValue.setText(intentData);  
  117.                                 isEmail = true;  
  118.                                 btnAction.setText("ADD CONTENT TO THE MAIL");  
  119.                             } else {  
  120.                                 isEmail = false;  
  121.                                 btnAction.setText("LAUNCH URL");  
  122.                                 intentData = barcodes.valueAt(0).displayValue;  
  123.                                 txtBarcodeValue.setText(intentData);  
  124.                             }  
  125.                         }  
  126.                     });  
  127.                 }  
  128.             }  
  129.         });  
  130.     }  
  131.   
  132.   
  133.     @Override  
  134.     protected void onPause() {  
  135.         super.onPause();  
  136.         cameraSource.release();  
  137.     }  
  138.   
  139.     @Override  
  140.     protected void onResume() {  
  141.         super.onResume();  
  142.         initialiseDetectorsAndSources();  
  143.     }  
  144. }  

In the EmailActivity.java class, add the following code. This class performs the email sending task to the address mention in the QR code.

EmailActivity.java

  1. package example.com.qrcodebarcodescanner;  
  2.   
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.support.v7.app.AppCompatActivity;  
  6. import android.view.View;  
  7. import android.widget.Button;  
  8. import android.widget.EditText;  
  9. import android.widget.TextView;  
  10.   
  11. public class EmailActivity extends AppCompatActivity implements View.OnClickListener {  
  12.   
  13.     EditText inSubject, inBody;  
  14.     TextView txtEmailAddress;  
  15.     Button btnSendEmail;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.activity_email);  
  21.         initViews();  
  22.     }  
  23.   
  24.     private void initViews() {  
  25.         inSubject = findViewById(R.id.inSubject);  
  26.         inBody = findViewById(R.id.inBody);  
  27.         txtEmailAddress = findViewById(R.id.txtEmailAddress);  
  28.         btnSendEmail = findViewById(R.id.btnSendEmail);  
  29.   
  30.         if (getIntent().getStringExtra("email_address") != null) {  
  31.             txtEmailAddress.setText("Recipient : " + getIntent().getStringExtra("email_address"));  
  32.         }  
  33.   
  34.         btnSendEmail.setOnClickListener(new View.OnClickListener() {  
  35.             @Override  
  36.             public void onClick(View v) {  
  37.                 Intent intent = new Intent(Intent.ACTION_SEND);  
  38.                 intent.setType("text/plain");  
  39.                 intent.putExtra(Intent.EXTRA_EMAIL, new String[]{txtEmailAddress.getText().toString()});  
  40.                 intent.putExtra(Intent.EXTRA_SUBJECT, inSubject.getText().toString().trim());  
  41.                 intent.putExtra(Intent.EXTRA_TEXT, inBody.getText().toString().trim());  
  42.   
  43.                 startActivity(Intent.createChooser(intent, "Send Email"));  
  44.             }  
  45.         });  
  46.     }  
  47.   
  48.     @Override  
  49.     public void onClick(View v) {  
  50.   
  51.         switch (v.getId()) {  
  52.             case R.id.btnScanBarcode:  
  53.                 startActivity(new Intent(EmailActivity.this, ScannedBarcodeActivity.class));  
  54.                 break;  
  55.         }  
  56.     }  
  57. }  

Add the following code in AndroidMenifest.xml file.

AndroidMenifest.java

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="example.com.qrcodebarcodescanner">  
  4.   
  5.     <uses-feature  
  6.         android:name="android.hardware.camera"  
  7.         android:required="true" />  
  8.   
  9.     <uses-permission android:name="android.permission.CAMERA" />  
  10.     <uses-feature android:name="android.hardware.camera.autofocus" />  
  11.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
  12.     <uses-permission android:name="android.permission.INTERNET" />  
  13.   
  14.     <application  
  15.         android:allowBackup="true"  
  16.         android:icon="@mipmap/ic_launcher"  
  17.         android:label="@string/app_name"  
  18.         android:roundIcon="@mipmap/ic_launcher_round"  
  19.         android:supportsRtl="true"  
  20.         android:theme="@style/AppTheme">  
  21.         <activity android:name=".MainActivity">  
  22.             <intent-filter>  
  23.                 <action android:name="android.intent.action.MAIN" />  
  24.   
  25.                 <category android:name="android.intent.category.LAUNCHER" />  
  26.             </intent-filter>  
  27.         </activity>  
  28.   
  29.         <activity android:name=".ScannedBarcodeActivity" />  
  30.         <activity  
  31.             android:name=".EmailActivity"  
  32.             android:windowSoftInputMode="adjustPan" />  
  33.     </application>  
  34.   
  35. </manifest>  

ouput:





I hope this will helpfull to you please share this article if posible.


Comments

Popular posts from this blog

How much does it cost to build an Android app?

The application advancement process can be broken out into four noteworthy parts – thought, format and arranging, structure, and going live. How much does it cost to build an Android app? The Idea  This is the beginning of where the application will go and one stage after "I need an application." Looking at the application store, there are many distinctive headings you can go – straightforward data, a diversion, intelligent, and so forth. You can envision that the more convoluted it is, the more it will cost – yet in addition a higher possibility of getting an arrival on the venture. Diversions are entangled, yet can turn into a web sensation effectively cost to build an Android app. Straightforward applications don't do much, yet they are shoddy and simple to manufacture. The initial step of the procedure is to locate your sweet spot of the spending plan and advertising exertion. In the event that you require more help tweaking your thought, conversing with...

Android tutorial or android development tutorial

Welcome to Training for Android developers . Here you'll find sets of lessons within classes that  describe how to accomplish a specific task with code samples you can re-use in your app. Android tutorial or android development tutorial covers basic and advanced concepts of android technology. Our android tutorial is developed for beginners and professionals. Android  is a complete set of software for mobile devices such as tablet computers, notebooks, smartphones, electronic book readers, set-top boxes etc. It contains a  Linux-based Operating System ,  middleware  and  key mobile applications . It can be thought of as a mobile operating system. But it is not limited to mobile only. It is currently used in various devices such as mobiles, tablets, televisions etc. From android development tutorial here anyone can learn how to develop an android app. Introduction Android is an open source mobile operating system ...

why android is the most popular,mobile operating system in the world?

Why android is the most popular, mobile operating system in the world? Android is the most successful mobile operating system at work(predicate) system in the traffic today. Let us try and find out whether this success is a product of technical quality or equitable Google magic. First, obstacle’s simile general aspects like security app provision, and ironmongery support with other smartphones OSs. Then, we will take a look at Android’s app development strategy and acquire it with that of the Firefox OS. Finally, we will interruption whether other artless sources OSs like Firefox OS and Ubuntu Touch could ever overtake or add to Android.  Interface Interface It is actually dashing hopes that no OS programmer seems to be introducing something new and innovative in the case of interface design. Lock screens, main menus, notification bars… Every manufacturer seems to be to mimic others. In the case of desktop OSs, you can see the variance between each conversion, distro and...