Xamarin.Forms QR Code Scan 二维码扫描的Android App

环境配置

  • VS2017
  • Xamarin.Forms   .Net Standard 2.0

具体实现使用的是一个老项目了「ZXing.Net.Mobile」:https://github.com/Redth/ZXing.Net.Mobile

 

1. 新建项目 | QrCode3 & QrCode3.Android

     新建项目如下图。(iOS应用不进行开发,具体操作详情请参考上文连接)

Xamarin.Forms QR Code Scan 二维码扫描的Android App_第1张图片

Xamarin.Forms QR Code Scan 二维码扫描的Android App_第2张图片

2. 添加 NuGet 包 | QrCode3 & QrCode3.Android

Xamarin.Forms QR Code Scan 二维码扫描的Android App_第3张图片

3. 添加 Android 权限 | QrCode3.Android

Xamarin.Forms QR Code Scan 二维码扫描的Android App_第4张图片

       可另行添加闪光灯权限: FLASHLIGHT

4. MainActivity 初始化 | QrCode3.Android

   MainActivity 中的 OnCreate 函数中添加代码:

MobileBarcodeScanner.Initialize(this.Application);

Xamarin.Forms QR Code Scan 二维码扫描的Android App_第5张图片

5. 添加接口 interface IQrCodeScanningService | QrCode3

namespace QrCode3.Service
{
    public interface IQrCodeScanningService
    {
		Task ScanAsync();
	}
}

6. 实现接口 QrCodeScanningService | QrCode3.Android

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Xamarin.Forms;
using QrCode3.Service;
using ZXing.Mobile;
using System.Threading.Tasks;

[assembly: Dependency(typeof(QrCode3.Droid.Services.QrCodeScanningService))]

namespace QrCode3.Droid.Services
{
	public class QrCodeScanningService : IQrCodeScanningService
	{
		public async Task ScanAsync()
		{
			var optionsDefault = new MobileBarcodeScanningOptions();
			var optionsCustom = new MobileBarcodeScanningOptions()
			{
				//UseFrontCameraIfAvailable = true,
				//Check diferents formats in http://barcode.tec-it.com/en
				// PossibleFormats = new List {  ZXing.BarcodeFormat.CODE_128 }
			};
			var scanner = new MobileBarcodeScanner()
			{
				TopText = "对准二维码 / 条形码",
				BottomText = "触摸屏幕来聚焦"
			};

			var scanResults = await scanner.Scan(optionsCustom);

			//Fix by Ale 2017-07-06
			return (scanResults != null) ? scanResults.Text : string.Empty;
		}

	}
}

Xamarin.Forms QR Code Scan 二维码扫描的Android App_第6张图片

7. 修改主页面并添加调用的按钮 | QrCode3




    
		
		
		private async void BtnScan_Clicked(object sender, EventArgs e)
		{
			var scanner = DependencyService.Get();
			var result = await scanner.ScanAsync();
			if(result != null)
				barcode.Text = result;
		}

8. 添加自定义扫描页面并调用 | QrCode3

     自定义页面参考 https://gist.github.com/jfversluis/8e9acedafc3ef3fd6e279d9ccf08ff53



    
		
			
				
				
				
			

			
				
			
		
	
		public void Handle_OnScanResult(Result result)
		{
			Device.BeginInvokeOnMainThread(async () =>
			{
				await DisplayAlert("Scanned result", result.Text, "OK");
			});
		}

 

你可能感兴趣的:(Xamarin,C#,Xamarin.Forms,Android,QR,Code,二维码,扫描)