读取QR码并自动从结果直接浏览到浏览器

时间:2017-07-18 07:54:27

标签: android xamarin.android qr-code zxing

我最近刚开始编程和开发应用程序。如果有人能帮助我,我将不胜感激。我用ZXing做了QR扫描仪,并且能够显示结果,但如果从QR码中检测到URL,我希望它自动打开浏览器

以下是我的扫描仪活动代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.Support.V7.App;
using Android.Views;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Widget;
using Android.Gms.Vision.Barcodes;
using Android.Gms.Vision;
using Android.Graphics;
using Android.Content.PM;
using Android.Support.V4.App;
using Android;
using static Android.Gms.Vision.Detector;
using Android.Util;

namespace com.xamarin.sample.splashscreen
{
    [Activity(Label = "Scanner")]
    public class Scanner : AppCompatActivity,ISurfaceHolderCallback, IProcessor
    {
        SurfaceView cameraPreview;
        TextView txtResult;
        BarcodeDetector barcodeDetector;
        CameraSource cameraSource;
        const int RequestCameraPermissionID = 1001;

        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Permission[] grantResults)
        {
           switch(requestCode)
            {
                case RequestCameraPermissionID:
                    {
                        if (grantResults[0]==Permission.Granted)
                        {
                            if (ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
                            {
                                ActivityCompat.RequestPermissions(this, new string[]
                                {
                     Manifest.Permission.Camera
                                 }, RequestCameraPermissionID);
                                return;
                            }
                            try
                            {
                                cameraSource.Start(cameraPreview.Holder);
                            }
                            catch (InvalidOperationException)
                            {

                            }
                        }
                    }
                    break;
            }
        }

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Scanner);

            cameraPreview = FindViewById<SurfaceView>(Resource.Id.cameraPreview);
            txtResult = FindViewById<TextView>(Resource.Id.txtResult);

            barcodeDetector = new BarcodeDetector.Builder(this)
                .SetBarcodeFormats(BarcodeFormat.QrCode).Build();

            cameraSource = new CameraSource.Builder(this, barcodeDetector)
                .SetRequestedPreviewSize(640, 480).Build();

            cameraPreview.Holder.AddCallback(this);
            barcodeDetector.SetProcessor(this);
        }

        public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height)
        {

        }

        public void SurfaceCreated(ISurfaceHolder holder)
        {
          if (ActivityCompat.CheckSelfPermission(ApplicationContext, Manifest.Permission.Camera) != Android.Content.PM.Permission.Granted)
                {
                ActivityCompat.RequestPermissions(this, new string[]
                {
                     Manifest.Permission.Camera
                 }, RequestCameraPermissionID);
                return;
            }
            try
            {
                cameraSource.Start(cameraPreview.Holder);
            }
            catch (InvalidOperationException)
            {

            }
        }

        public void SurfaceDestroyed(ISurfaceHolder holder)
        {
            cameraSource.Stop();
        }

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

        public void Release()
        {

        }
    }`enter code here`
}`enter code here`

1 个答案:

答案 0 :(得分:0)

  

如果从QR码中检测到网址,我希望自动打开浏览器

当您从QR码获得ZXing.Result时,您可以使用Patterns.WebUrl.Matcher方法确认这是URL

当您使用Patterns.WebUrl.Matcher(result.Text).Matches()方法时,此正则表达式模式与RFC 3987国际化URL(即IRI)的大部分内容相匹配。

这样的代码:

private void HandleScanResult(ZXing.Result result)
    {
        string msg = "";

        if (result != null && !string.IsNullOrEmpty(result.Text))
            msg = "Found Barcode: " + result.Text;
        else
            msg = "Scanning Canceled!";

        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.PutString("result", result.Text);
        resultIntent.PutExtras(bundle);
        this.SetResult(Result.Ok, resultIntent);

        if (Patterns.WebUrl.Matcher(result.Text).Matches())
        {
            //If this result get from the QR code is an URL, open the browse.                    
            Intent intent = new Intent();
            intent.SetAction("android.intent.action.VIEW");
            Android.Net.Uri content_url = Android.Net.Uri.Parse(result.Text);
            intent.SetData(content_url);
            StartActivity(intent);
        }
        else
        {
            this.RunOnUiThread(() => Toast.MakeText(this, msg, ToastLength.Short).Show());
        }
    }