Xamarin.Android ZXing.Net Mobileを使ってみた
簡単にスキャナが作れると言うことで、ZXing.Net Mobileを使ってみました。
https://github.com/Redth/ZXing.Net.Mobile
こちらにあるSampleコードとほとんど同じです。
インストール
NuGetからZXing.Net.Mobileをインストール
Manifest設定
プロジェクトのプロパティの[Android Manifest]から
[Required permissions]で
CAMERA
FLASHLIGHT
をチェックオン
画面レイアウト
サンプルはいくつかボタンがありますが、取りあえず標準動作と思われる物のボタンのみ配置
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()); }
ビルドして実行・・・
認識早いですね。こりゃ便利。 他の機能も試してみようと思います(・ω・)ノ
不明点
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); }