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)
- {
- //Request Permision
- 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);
- // Set our view from the "main" layout resource
- 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)
- {
- //Request Permision
- 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.

Richard PopovichPosted Apr 16, 2024, 5:10 PM
Downloading QrReaderByCamera.zip and attempting to build I get the error 'Resource.Drawable' does not contain a definition for 'qrcode' and see no items in the Resources folder
Abdul Amin KhanPosted May 29, 2023, 9:36 AM
This camera code has blur issue and not setting focus on it. please tell me solution for that if you can
Ranjit BhonsalePosted Oct 2, 2021, 5:43 PM
Rest all ok, any idea how to start the FlashLight, once the camera turns on it does not work
Kamol RoyPosted Sep 20, 2021, 9:31 AM
If i want to focus camera with zoom ??
Rahul PrakashPosted Aug 19, 2019, 11:54 PM
How can crete this application to button click Xamarin android
Gurdeep SinghPosted May 10, 2019, 2:52 AM
SparseArray qrcodes = detections.DetectedItems;qrcodes.Size() is always returning 0 even though the barcode is clearly focussed.
atin agarwalPosted Mar 6, 2019, 4:13 AM
SparseArray qrcodes = detections.DetectedItems;qrcodes.Size() is always returning 0 even though the barcode is clearly focussed.
Hashim AnwarPosted Feb 18, 2019, 5:53 AM
How can I declare this activity in the manifest if I am opening it up using a button click from another activity?
Emmanuel AdebiyiPosted Feb 10, 2019, 2:21 PM
Resource.Drwable does not contain a definition for qrcode. Cant seem to get around it
Amin BazgiriPosted Jan 29, 2019, 2:26 PM
I followed the steps, but I point the camera at a good qr code for a long time, nothing happens
Nahuel LeivaPosted Jan 25, 2019, 9:08 AM
I'm developing a QR code reader using this code and I want to implement the Release method to prevent battery consumption in case the app detects that I'm not using the camera for a certain time. How do I implement this method? What tools do I have to use to implement it? Thanks in advance.
Süleyman ÇANPosted Dec 10, 2018, 12:43 AM
Hi, thanks for your code. How the camera autofocus on the barkod.
p dPosted Nov 6, 2018, 10:11 AM
The attached zip file has the subfolder "QrReaderByCamera" instead of "QR_Code_Reader". Renaming the project opens but does not fill in with error: "Severity Code Description Project File Line Delete statusError CS0117 'Resource.Drawable' does not contain a definition for 'qrcode' QrReaderByCamera C:\QrReaderByCamera\QR_Code_Reader\MainActivity.cs 71 Active "Deleted "bin" and "obj" and "Resources\Resource.Designer.cs", clean but does not compile the project,
Nicolas SantostefanoPosted Sep 12, 2018, 4:40 PM
I made it work, thanks. The only problem i have now is how to pause the detecction afer i found a valid info in the QR. If i put: cameraSource.Stop(); then when i get back to this activity camera wont detect again or crash !
Nicolas SantostefanoPosted Sep 10, 2018, 6:09 PM
Hello, i get and Error on line 62: " Bitmap bitMap = BitmapFactory.DecodeResource(ApplicationContext.Resources, Resource.Drawable.qrcode); " but marcos?s solution didnt work for me, I Copy your code from here
Marcos TadeuPosted Aug 9, 2018, 9:57 AM
Hi, Very Good Tuto !!! But i have a same problems when reproduce steps in lines 20, (AppCompatActivity ) and lines 61,62,63,64: .Resources, Resource.Drawable.qrcode) . In Visual Studio 2017 with Xamarin 2018 same erros
Michael GrinnellPosted Jun 14, 2018, 10:21 AM
Any Idea Why I Would be getting a null pointer exception when I scan the qr code. it is in the method ReceiveDetections on txtResult.Post.
Ram kumarPosted May 17, 2018, 6:43 AM
After release my app is opening but not scanned.Please help me
Julio CézarPosted Apr 16, 2018, 1:20 PM
Congratulations on the article!How to implement a Qr Code reading interval in seconds?
Sagar Pandurang KapPosted Jan 1, 2018, 12:54 AM
Very ice.thank you...