Introduction
Today, I shall show you how to create a QR Code Reader app in Xamarin, that uses a mobile camera.
The Prerequisites
- Android Support Library v7 AppCompat
- Xamarin Android Support v4
- Google Play Services - Vision
The steps given below are required to be followed in order to create a QR code reader app by a mobile camera in Xamarin.Android, using Visual Studio.
Step 1 - Create Android Project
Create your Android solution in Visual Studio or Xamarin Studio. Select Android and from the list, choose Android Blank App. Give it a name, like QrReaderByCamera.
(ProjectName: QrReaderByCamera)
Step 2 - Add Android.Support.v7.AppCompat Library
First of all, in References, add a reference to Android.Support.v7.AppCompat using NuGet Package Manager, as shown below.
Step 3 - Add Xamarin Android Support v4
Similarly, install Xamarin Android Support v4 Library.
Step 4 - Add Xamarin Google Play Services - Vision
Next in References, add another reference to Xamarin GooglePlayServices Vision using NuGet Package Manager, as shown below.
Step 5 - Layout
Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml and add the following code. The layout will have a SurfaceView in order to display the preview frames captured by the camera. I also added a TextView to display the contents of the QR Code.
(FileName: Main.axml)
XML Code
- <?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">
- <SurfaceView
- android:id="@+id/cameraView"
- android:layout_width="match_parent"
- android:layout_height="480dp"
- android:layout_centerInParent="true" />
- <TextView
- android:layout_centerInParent="true"
- android:gravity="center_horizontal"
- android:id="@+id/txtResult"
- android:layout_below="@+id/cameraView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="Please focus Camera to QR Code"
- android:textSize="20sp"
- android:layout_marginTop="20dp" />
- </RelativeLayout>
Step 6 - Main Activity Class
Now, go to Solution Explorer-> Project Name-> MainActivity and add the following code with appropriate namespaces.
(FileName: MainActivity)
C# Code
- using Android;
- using Android.App;
- using Android.Content;
- using Android.Content.PM;
- using Android.Gms.Vision;
- using Android.Gms.Vision.Barcodes;
- using Android.Graphics;
- using Android.OS;
- using Android.Runtime;
- using Android.Support.V4.App;
- using Android.Support.V7.App;
- using Android.Util;
- using Android.Views;
- using Android.Widget;
- using System;
- using static Android.Gms.Vision.Detector;
- namespace QrReaderByCamera
- {
- [Activity(Label = "QrReaderByCamera", MainLauncher = true , Theme ="@style/Theme.AppCompat.Light.NoActionBar")]
- public class MainActivity : AppCompatActivity , ISurfaceHolderCallback, IProcessor
- {
- SurfaceView surfaceView;
- TextView txtResult;
- BarcodeDetector barcodeDetector;
- CameraSource cameraSource;
- const int RequestCameraPermisionID = 1001;
- public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
- {
- switch (requestCode)
- {
- case RequestCameraPermisionID:
- {
- if(grantResults[0] == Permission.Granted)
- {
- if (ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
- {
-
- ActivityCompat.RequestPermissions(this, new string[]
- {
- Manifest.Permission.Camera
- }, RequestCameraPermisionID);
- return;
- }
- try
- {
- cameraSource.Start(surfaceView.Holder);
- }
- catch (InvalidOperationException)
- {
- }
- }
- }
- break;
- }
- }
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
-
- SetContentView(Resource.Layout.Main);
- surfaceView = FindViewById<SurfaceView>(Resource.Id.cameraView);
- txtResult = FindViewById<TextView>(Resource.Id.txtResult);
- Bitmap bitMap = BitmapFactory.DecodeResource(ApplicationContext
- .Resources, Resource.Drawable.qrcode);
- barcodeDetector = new BarcodeDetector.Builder(this)
- .SetBarcodeFormats(BarcodeFormat.QrCode)
- .Build();
- cameraSource = new CameraSource
- .Builder(this, barcodeDetector)
- .SetRequestedPreviewSize(640, 480)
- .Build();
- surfaceView.Holder.AddCallback(this);
- barcodeDetector.SetProcessor(this);
- }
- public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
- {
- }
- public void SurfaceCreated(ISurfaceHolder holder)
- {
- if(ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
- {
-
- ActivityCompat.RequestPermissions(this, new string[]
- {
- Manifest.Permission.Camera
- }, RequestCameraPermisionID);
- return;
- }
- try
- {
- cameraSource.Start(surfaceView.Holder);
- }
- catch (InvalidOperationException)
- {
- }
- }
- public void SurfaceDestroyed(ISurfaceHolder holder)
- {
- cameraSource.Stop();
- }
- public void ReceiveDetections(Detections detections)
- {
- SparseArray qrcodes = detections.DetectedItems;
- if (qrcodes.Size() != 0)
- {
- txtResult.Post(() => {
- Vibrator vibrator = (Vibrator)GetSystemService(Context.VibratorService);
- vibrator.Vibrate(1000);
- txtResult.Text = ((Barcode)qrcodes.ValueAt(0)).RawValue;
- });
- }
- }
- public void Release()
- {
-
- }
- }
- }
Step 7 - Permission From Device
We need a permission from the device because we shall be using the device’s camera to capture QR Code. Please add Camera permissions to your AndroidManifest.xml. Open the Solution Explorer-> Properties-> AndroidManifest and let's add the code inside application tags.
- <uses-permission android:name="android.permission.CAMERA" />
- <uses-permission android:name="android.permission.VIBRATE" />
- <application android:allowBackup="true" android:label="@string/app_name">
- <meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="barcode" />
- </application>
OutPut
Running this project, and scanning a QR code, you will have the result like below.
Summary
This was the process of creating a QR Code Reader by Mobile Camera app in Xamarin.Android. Please share your comments and feedback.