Xamarin : Android : Using ZXing.Net.Mobile Scan Barcode 掃描讀取條碼/QR碼

網路上大部份文章在講 Xamarin 開發都用上了 CPL類型的專案,
對於純粹使用 Android 專案使用者要理解真是有點不方便,

這裡是記錄了在 Xamarin 下的 Android 專案如何開發一個讀取 條碼或是 QR碼的功能

個功能是基於 ZXing.Net.Mobile 套件開發的,可以自行把這個套件應用你的專案中

1、假設你經開啟了一個 Android blank Project (空白專案)

2、使用 NuGet 管理員去新增 ZXing.Net.Mobile 套件,並把它安裝到專案中


3、然後到你要呼叫使用 ZXing 操作的 Activity 去新增引用(在這案例裡我是放在 MainActivity.cs 內)

using ZXing;
using ZXing.Mobile;


4、在顯示畫面(Main.axml)上設計兩個 TextView 和一個 Button,用來啟動掃描和接收掃描的結果


5、然後就是把操作 ZXing 的程式碼加入,在這案例中,我只簡單全部做在 MainActivity 的 OnCreate 內,實際應用上你可以依照需要放置。

using Android.App;
using Android.Widget;
using Android.OS;
using ZXing;
using ZXing.Mobile;

namespace ZxingTest
{
    [Activity(Label = "ZxingTest", MainLauncher = true, Icon = "@drawable/icon")]

    public class MainActivity : Activity
    {
        //建立操作物件指標
        private TextView _barcodeFormat, _barcodeData;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // 設定顯示畫面
            SetContentView (Resource.Layout.Main);

            //掃描元件初始化
            MobileBarcodeScanner.Initialize(Application);

            //簡化操作的位置(變數指標)
            _barcodeFormat = FindViewById<TextView>(Resource.Id.barcode_format);
            _barcodeData = FindViewById<TextView>(Resource.Id.barcode_data);

            //建立按鈕 Click 事件
            var button = FindViewById<Button>(Resource.Id.button_scan);
            button.Click += async (Senders, args) =>
            {
                //設定掃描元件操作
                var opts = new MobileBarcodeScanningOptions
                {
                    //限定(啟用)可掃描識別種類
                    PossibleFormats = new System.Collections.Generic.List<BarcodeFormat>
                    {
                        BarcodeFormat.CODE_128,
                        BarcodeFormat.CODE_39,
                        BarcodeFormat.EAN_13,
                        BarcodeFormat.EAN_8,
                        BarcodeFormat.QR_CODE
                    }
                };
                //建立可執行化實例
                var scanner = new MobileBarcodeScanner();
                //利用 await 執行掃描,等待回應
                var result = await scanner.Scan(opts);

                //將回傳結果輸出到 TextView
                _barcodeFormat.Text = result?.BarcodeFormat.ToString() ?? string.Empty;
                _barcodeData.Text = result?.Text ?? string.Empty;
            };
        }
    }
}


6、實際操作
主畫面


掃描


返回掃描結果


參考文章來源:
Xamarin Android 二维码扫描示例– Design based .NET

留言

這個網誌中的熱門文章

【研究】列印的條碼為什麼很難刷(掃描)

C# 使用 Process.Start 執行外部程式

統一發票列印小程式