tonkunの備忘録

色々調べた事、試した事などを載せます

Xamarin.Android ZXing.Net Mobileを使ってみた

簡単にスキャナが作れると言うことで、ZXing.Net Mobileを使ってみました。

https://github.com/Redth/ZXing.Net.Mobile

こちらにあるSampleコードとほとんど同じです。

インストール

NuGetからZXing.Net.Mobileをインストール

f:id:tonkun_no:20160703013331p:plain

Manifest設定

プロジェクトのプロパティの[Android Manifest]から [Required permissions]で
CAMERA
FLASHLIGHT
をチェックオン

f:id:tonkun_no:20160703014211p:plain

画面レイアウト

サンプルはいくつかボタンがありますが、取りあえず標準動作と思われる物のボタンのみ配置

f:id:tonkun_no:20160703015128p:plain

MainActivity

以下のように記載

protected override void OnCreate(Bundle bundle)
{
    base.OnCreate(bundle);
    // Set our view from the "main" layout resource
    SetContentView(Resource.Layout.Main);
    var scanner = new MobileBarcodeScanner();
    // Resource取得
    var buttonScanDefaultView = this.FindViewById<Button>(Resource.Id.buttonScanDefaultView);
    // Clickイベント設定
    buttonScanDefaultView.Click += async (sender, e) =>
    {
        scanner.UseCustomOverlay = false;
        scanner.TopText = "Hold the camera up to the barcode";
        scanner.BottomText = "Wait for the barcode to automatically scan!";
        var result = await scanner.Scan();
        HandleScanResult(result);
    };
}

/// <summary>
/// 読み込み結果に対する処理
/// </summary>
/// <param name="result"></param>
public void HandleScanResult(ZXing.Result result)
{
    string msg = string.Empty;
    if (result != null && !string.IsNullOrEmpty(result.Text))
        msg = "Found Barcode: " + result.Text;
    else
        msg = "Scanning Canceled";
    this.RunOnUiThread(() => Toast.MakeText(this, msg, ToastLength.Short).Show());
}

ビルドして実行・・・

f:id:tonkun_no:20160703020400p:plain

f:id:tonkun_no:20160703020507p:plain

f:id:tonkun_no:20160703020533p:plain

認識早いですね。こりゃ便利。 他の機能も試してみようと思います(・ω・)ノ

不明点

Runtime Permissionの設定方法が良くわかりません・・・
ZXing.Net.Mobile.Formsの場合は、以下の内容で良いらしいですが。

public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Permission[] grantResults)
{
    global::ZXing.Net.Mobile.Forms.Android.PermissionsHandler.OnRequestPermissionsResult (requestCode, permissions, grantResults);           
}