首页 > 解决方案 > BarcodeDetector 仅应在单击按钮时进行扫描

问题描述

我正在尝试使用集成的条形码扫描仪编写应用程序。我遵循了本教程: https ://www.c-sharpcorner.com/article/xamarin-android-qr-code-reader-by-mobile-camera/

扫描工作正常且速度非常快(在我使用 ZXing.Net.Mobile 之前,速度非常慢)。现在我需要一些帮助来集成应用程序仅在用户按下按钮而不是整个时间时检测到一个条形码。也许延迟也能解决问题。

protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            // Set our view from the "main" layout resource  
            SetContentView(Resource.Layout.ScannerTest);
            surfaceView = FindViewById<SurfaceView>(Resource.Id.cameraView);
            txtResult = FindViewById<TextView>(Resource.Id.txtResult);
            barcodeDetector = new BarcodeDetector.Builder(this)
                .SetBarcodeFormats(BarcodeFormat.Code128 | BarcodeFormat.Ean13 | BarcodeFormat.QrCode)
                .Build();
            cameraSource = new CameraSource
                .Builder(this, barcodeDetector)
                .SetRequestedPreviewSize(320, 480)
                .SetAutoFocusEnabled(true)
                .Build();

            surfaceView.Click += StartScanning;
            surfaceView.Holder.AddCallback(this);
            //barcodeDetector.SetProcessor(this);
        }
private void StartScanning(object sender, EventArgs e)
{
        barcodeDetector.SetProcessor(this);
}
public void ReceiveDetections(Detections detections)
        {
            SparseArray qrcodes = detections.DetectedItems;
            if (qrcodes.Size() != 0)
            {
                txtResult.Post(() => {
                    //Vibrator vibrator = (Vibrator)GetSystemService(Context.VibratorService);
                    //vibrator.Vibrate(1000);
                    txtResult.Text = ((Barcode)qrcodes.ValueAt(0)).RawValue;
                });
            }
        }

在用户按下 SurfaceView 的那一刻,扫描仪启动并且永不停止。

有没有可能,它只是在按下“按钮”后扫描一个?

r3d007

标签: c#xamarin.android

解决方案


1 在 OnCreate 方法中取消注释此行

barcodeDetector.SetProcessor(this);

2 从 SurfaceCreated 和 OnRequestPermissionsResult 方法中删除或注释此行

cameraSource.Start(surfaceView.Holder);

3 您的 StartScanning 方法应该调用 Start

private void StartScanning(object sender, EventArgs e)
{
    cameraSource.Start(surfaceView.Holder);
}

4 读取并验证代码后,停止扫描仪

public void ReceiveDetections(Detections detections)
{
    SparseArray qrcodes = detections.DetectedItems;
    if (qrcodes.Size() != 0)
    {
        txtResult.Post(() => {
            //Vibrator vibrator = (Vibrator)GetSystemService(Context.VibratorService);
            //vibrator.Vibrate(1000);
            txtResult.Text = ((Barcode)qrcodes.ValueAt(0)).RawValue;
        });

        using (var h = new Handler (Looper.MainLooper))
        h.Post (() => {
            cameraSource.Stop();
        });

    }
}

为防止崩溃,请考虑隐藏或禁用按钮,直到您获得相机权限并且扫描仪已经启动。


推荐阅读