Xamarin.android-with zxing for two-dimensional code scanning and continuous scanning

Source: Internet
Author: User

First, preface

The content of this article has two foundations: Zxing.net and ZXing.Net.Mobile

ZXing.Net:ZXing's C # implementation, mainly encapsulates a variety of QR code encoding, decoding and other cross-platform algorithm

ZXing.Net.Mobile: The application of zxing.net in Xamarin has been encapsulated, mainly for camera scanning, scanning view, scanning activity, scanning fragment, etc.

ZXing.Net.Mobile Download:Xamarin Components Market or GitHub

Two

Three, the basic realization

1. Pop up a new window to scan

 Public classMainFragment:Android.Support.V4.App.Fragment {Mobilebarcodescanner scanner;  Public OverrideView Oncreateview (layoutinflater inflater, ViewGroup p1, Bundle p2) {returnInflater. Inflate (Resource.Layout.Main,NULL); }         Public Override voidonviewcreated (view view, Bundle savedinstancestate) {Base.            onviewcreated (view, savedinstancestate); Scanner=NewMobilebarcodescanner ( This.            Activity);  This. View.findviewbyid<button> (Resource.Id.btnDefault). Click + =Btndefault_click;  This. View.findviewbyid<button> (Resource.Id.btnCustom). Click + =Btncustom_click; }        Async voidBtndefault_click (Objectsender, EventArgs e) {            //do not use custom interfacesScanner. Usecustomoverlay =false; //set up and down prompt textScanner. TopText ="the text above"; Scanner. Bottomtext="the following text"; varresult =awaitscanner.            Scan ();        Handlescanresult (result); }        Async voidBtncustom_click (Objectsender, EventArgs e)            {View zxingoverlay; //Use the Custom interface (you can add an animation to the box or something, this is free to play)Scanner. Usecustomoverlay =true; Zxingoverlay= Layoutinflater.fromcontext ( This. Activity). Inflate (Resource.Layout.ZxingOverlay,NULL); Scanner. Customoverlay=Zxingoverlay; varresult =awaitscanner.            Scan ();        Handlescanresult (result); }        voidHandlescanresult (Zxing.result Result) {stringmsg =""; if(Result! =NULL&&!string. IsNullOrEmpty (result. Text)) msg="Scan results:"+result.            Text; Elsemsg="Scan canceled!";  This. Activity.runonuithread (() ={Toast.maketext ( This. Activity, MSG, toastlength.short).                Show ();        }); }    }
View Code

The default pop-up scan is used in Btndefault_click, which is less customizable and can only modify the upper and lower text

Btncustom_click uses a custom interface pop-up scan, in fact, to the scanning interface above a layer of custom-defined layout

The processing of scan results in Handlescanresult, here is just a simple toast

2. Integrated scanning in Fragment

This uses the zxingscannerfragment already encapsulated in the ZXing.Net.Mobile library and uses the overlay to customize the interface.

 Public classScannerFragment:Android.Support.V4.App.Fragment {zxingscannerfragment scanfragment;        View Zxingoverlay;  Public OverrideView Oncreateview (layoutinflater inflater, ViewGroup p1, Bundle p2) {returnInflater. Inflate (Resource.Layout.Scanner,NULL); }         Public Override voidonviewcreated (view view, Bundle savedinstancestate) {Base.            onviewcreated (view, savedinstancestate); Zxingoverlay= Layoutinflater.fromcontext ( This. Activity). Inflate (Resource.Layout.ZxingOverlay,NULL); Scanfragment=Newzxingscannerfragment (Scanresultcallback); Scanfragment.usecustomview=true; Scanfragment.customoverlayview=Zxingoverlay;  This. Activity.SupportFragmentManager.BeginTransaction (). Replace (Resource.Id.fragment_container, scanfragment).        Commit (); }        Private voidScanresultcallback (Zxing.result Result) {if(Result = =NULL||string. IsNullOrEmpty (result. Text)) { This. Activity.runonuithread (() ={Toast.maketext ( This. Activity,"The scan has been canceled! ", Toastlength.short).                    Show (); ((homefragment) This. fragmentmanager.fragments[0]). Setcurrenttab ("Main");                }); return; }            Else            {                //Scan succeeded                 This. Activity.runonuithread (() =                {                    //VibrationVibrator Vibrator =(Vibrator) Application.Context.GetSystemService (Context.vibratorservice); Long[] pattern = {0, -, -, - }; Vibrator. Vibrate (pattern,-1); Console.WriteLine (Result.                    Text); Toast.maketext ( This. Activity, result. Text, Toastlength.short).                    Show (); ((homefragment) This. fragmentmanager.fragments[0]). Setcurrenttab ("Main");                }); return; }        }    }
View Code

Initializes the zxingscannerfragment, passing it a action<zxing.result> type of Scanresultcallback callback,

Processing of scan results in Scanresultcallback: vibration, output, Toast, toggle fragment, etc.

Four, continuous scanning

Now basically can scan, but now there is a need: After the scan if the scan results are not mobile phone number then continue scanning.

OK, modify the callback processing after the scan is complete

//here plus QR code format requirements, if not meet the requirements, continue to scan (I am here to determine whether the mobile phone number)                    if(Istelephone (Result). Text) {Toast.maketext ( This. Activity, result. Text, Toastlength.short).                        Show (); ((homefragment) This. fragmentmanager.fragments[0]). Setcurrenttab ("Main"); }                    Else{Toast.maketext ( This. Activity,"scanned QR code format is incorrect! ", Toastlength.short).                    Show (); }
/// <summary>        /// Verify the format        of the phone number /// </summary>         Public BOOL Istelephone (string  str_telephone)        {            return@ "^ (0|86| 17951)? (13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]) [0-9] {8}$");        }

Originally thought this is done, did not expect the scan result is not the mobile phone number, the prompt "scan of the QR code format is not correct!" "And then stopped scanning.

It seems that the ZXing.Net.Mobile library will stop scanning as soon as the scan is complete (I think the author is trying to prevent the problem of repeated scanning).

In order to achieve continuous scanning, we can only modify the ZXing.Net.Mobile library.

Below is just "fragment in the integrated scan" in the implementation, "Pop up a new window to scan" There are similar problems, the small partners themselves to view the source play it, haha!

After analysis, it is found that the Onpreviewframe method in the Zxingsurfaceview class calls the Shutdowncamera () before the callback is triggered after the scan is completed.

This is the main culprit to stop the scan, OK, erase it, this is a continuous scan, but even if the scan results are mobile phone number scanning will continue, so there is a possibility of repeated scanning problems,

Therefore, when the scan results meet the requirements in this case, manual "stop scanning" is required: Zxingscannerfragment.shutdown ()

//here plus QR code format requirements, if not meet the requirements, continue to scan (I am here to determine whether the mobile phone number)                    if(Istelephone (Result). Text)) {//proactively turn off the camera to prevent duplicate scansScanfragment.shutdown (); Toast.maketext ( This. Activity, result. Text, Toastlength.short).                        Show (); ((homefragment) This. fragmentmanager.fragments[0]). Setcurrenttab ("Main"); }                    Else{Toast.maketext ( This. Activity,"scanned QR code format is incorrect! ", Toastlength.short).                    Show (); }

SOURCE download

Https://github.com/jordanqin/ZXing.Scanner

Reference:

http://components.xamarin.com/view/zxing.net.mobile/

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

If you find the article helpful, you can click the "recommend" button next to it, which will give more people the opportunity to see

Xamarin.android-with zxing for two-dimensional code scanning and continuous scanning

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.