How to Use Android AAR File in Xamarin Project
Dynamsoft Barcode SDK for Android is distributed as an AAR file. This article aims to help C# developers, who want to build mobile barcode apps with Xamarin, to use the AAR file in Visual Studio 2015.
Dynamsoft Xamarin Barcode SDK is Available on NuGet
SDK: Xamarin.Dynamsoft.Barcode.Android
Examples: https://github.com/dynamsoft-dbr/xamarin
If you want to build the Xamarin library from scratch, keep reading the following paragraphs.
Creating Xamarin Bindings Library from Android AAR file
Basic steps
Referring to the article Binding an AAR:
- Create a new Java Bindings Library project.
- Add the AAR file to the project.
- Set the appropriate build action for the AAR file.
- Choose a target framework that the AAR supports.
- Build the Bindings Library.
Convert DynamsoftBarcodeReader.aar to DBRAndroid.dll
Launch Visual Studio 2015 to create a new project DBRAndroid
with the template – Bindings Library (Android).
Download SDK package for Android. Drag DynamsoftBarcodeReader.aar to your project. Change the Build Action to LibraryProjectZip.
Build the project to generate DBRAndroid\bin\Debug\DBRAndroid.dll.
Using the Bindings Library
Create a blank Android project. Add DBRAndroid.dll to References.
Double-click the reference, you can see the classes, members, and functions defined in Java have been converted to C# types:
In order to quickly test the barcode APIs, I just copied a QR image qr.png to the drawable folder. This is a simple demo. To fulfill a real Android barcode reader app, you can use camera APIs to take barcode images or use Activity Intent to pick images from gallery.
How to convert a drawable to a bitmap with Xamarin API?
When using Android SDK in Java, the code is as follows:
Bitmap icon = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon_resource);
Using Xamarin is a little bit different. Here is the C# code:
Bitmap image = BitmapFactory.DecodeResource(Resources, Resource.Drawable.qr);
How to read barcode with the bindings library?
Include the namespace:
using Com.Dynamsoft.Barcode;
Specify the barcode format and then decode the image:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate {
Bitmap image = BitmapFactory.DecodeResource(Resources, Resource.Drawable.qr);
BarcodeReader barcodeReader = new BarcodeReader("license");
ReadResult result = barcodeReader.ReadSingle(image, Barcode.QrCode);
button.Text = string.Format("{0} clicks! barcode result: {1}", count++, result.Barcodes[0].DisplayValue);
};
}
It’s done. You can now deploy the app to your Android device or emulator via Visual Studio 2015.