Android QR code generation and identification (with demo source)

Source: Internet
Author: User
Tags image processing library

Today talk about the current mobile domain is a very common technology-QR code. Now the streets, the major sites have two-dimensional code traces, whether it is iOS, Android, WP have relevant support software. Before I wanted to know how the QR code works, recently because the work needs to use the relevant technology, so did a preliminary understanding. Today, we mainly explain how to use the Zxing library to generate and identify QR codes. This article is mainly practical, the theory will not explain too much, have the interest to view the source code.

1, zxing Library Introduction

Here is a brief introduction to the Zxing library. Zxing is an open source, Java-implemented, multi-format 1d/2d barcode Image processing library that contains ports that are linked to other languages. Zxing can be implemented using the phone's built-in camera to complete the barcode scanning and decoding. This project can be implemented by barcode encoding and decoding. The following formats are currently supported: UPC-A,UPC-E, EAN-8,EAN-13, 39 yards, 93 yards. Zxing is a very classic barcode/two-D code recognition of the Open source class library, previously on the function machine, there are developers using J2ME zxing, but to support the JSR-234 specification (autofocus) of the mobile phone to play its power.

Below is Zxing's demo run, I created a QR code here, the content is my blog URL, you can use the sweep function, try. You can open my blog directly.
<ignore_js_op>

25213819-1eaa4d41d72c463ab291b40062d0f831.jpg (68.25 KB, download number: 278)

Download attachments to albums

2013-8-30 15:00 Upload

2, zxing Library main class

Here is a brief introduction to the main classes in the Zxing library and the functions of these classes:
    • Captureactivity. This is the startup activity, the scanner.
    • The Captureactivityhandler decoding processing class is responsible for invoking additional threads for decoding.
    • Decodethread the decoded thread.
    • Com.google.zxing.client.android.camera package, Camera control pack.
    • Viewfinderview's Custom view is what we see in the middle of the shooting.


3, using zxing to generate two-dimensional codeThe following for the two-dimensional code generation and analysis to do a brief introduction, as to the detailed use of methods, we suggest that you look at the source code, the use of it is very simple, but the code of this open source project is worth a good look. First, we give the method of two-dimensional code generation:
//edited by Mythou//http://www.cnblogs.com/mythou/    //the address or string to be converted, which can be in Chinese     Public voidcreateqrimage (String url) {Try        {            //Determine URL legitimacy            if(url = =NULL|| ". Equals (URL) | | Url.length () < 1)            {                return; } Hashtable<encodehinttype, string> hints =NewHashtable<encodehinttype, string>(); Hints.put (Encodehinttype.character_set,"Utf-8"); //conversion of image data using matrix conversionBitmatrix Bitmatrix =NewQrcodewriter (). Encode (URL, Barcodeformat.qr_code, qr_width, qr_height, hints); int[] pixels =New int[Qr_width *Qr_height]; //here according to the two-dimensional code algorithm, one by one to generate two-dimensional code of the picture,//Two for loop is the result of the picture Heng Lie scan             for(inty = 0; Y < Qr_height; y++)            {                 for(intx = 0; x < qr_width; X + +)                {                    if(Bitmatrix.get (x, y)) {pixels[y* qr_width + x] = 0xff000000; }                    Else{pixels[y* qr_width + x] = 0xFFFFFFFF; }                }            }            //Create a QR code image format, using argb_8888Bitmap Bitmap =Bitmap.createbitmap (Qr_width, Qr_height, Bitmap.Config.ARGB_8888); Bitmap.setpixels (Pixels,0, qr_width, 0, 0, Qr_width, qr_height); //display to a imageview aboveSweepiv.setimagebitmap (bitmap); }        Catch(writerexception e) {e.printstacktrace (); }    }

Above is the two-dimensional code generated by the method interface, if you are only the user method, it is simple, just pass in a URL, just like me inside, a legitimate URL can be passed. Or, as with some mobile app promotion, turn the app into a QR code and download the app as soon as you scan it.  This is also a popular way to promote the current app. The above code does not do a lot of things, mainly called Zxing library inside Qrcodewriter (). Encode method to encode the URL we passed in, specifically how to encode, this I do not say in detail here, interested can see the source of zxing. At the end of the article, we will give the source code and the example zxing. 4, scan QR code to get information scan to get QR code information is slightly more complicated, mainly need to write the use of the camera, this is similar to our general use of camera, we need to use Surfaceview as a preview, This one I don't say here, this should not be too complicated. It should be quite simple for a friend who has used a camera to do a preview. The key processing to get the QR code data is where the AF callback function of the camera is called, and the decoding interface of the zxing is invoked.

// edited by Mythou // http://www.cnblogs.com/mythou/ Private void Restartpreviewanddecode () {    if (state = = state.success)      {= state.preview;< C12/>cameramanager.get (). Requestpreviewframe (Decodethread.gethandler (), r.id.decode);      Cameramanager.get (). Requestautofocus (this, r.id.auto_focus);      Activity.drawviewfinder ();    }  }  

Here a little more to say, because the decoding takes a certain time, so zxing decoding calls, are used handler as a thread communication mechanism, the work of decoding is placed in a separate thread inside the use, if you directly in the main thread decoding, I am afraid that the ANR problem can not be avoided.

//edited by Mythou//http://www.cnblogs.com/mythou/ Public voidhandlemessage (Message message) {Switch(message.what) { CaseR.id.auto_focus://log.d (TAG, "Got auto-focus message"); //When one auto Focus pass finishes, start another. The closest thing to//continuous AF. It does seem to hunt a bit, but I'm not sure what else to do.        if(state = =State.preview) {cameramanager.get (). Requestautofocus ( This, R.id.auto_focus); }         Break;  Caser.id.restart_preview:log.d (TAG,"Got Restart Preview message");        Restartpreviewanddecode ();  Break;  Caser.id.decode_succeeded://decoding succeeds, obtains the result of the interface and the original QR code dataLOG.D (TAG, "Got Decode succeeded Message"); State=state.success; Bundle Bundle=Message.getdata (); Bitmap Barcode= Bundle = =NULL?NULL: (Bitmap) bundle.getparcelable (DECODETHREAD.BARCODE_BITMAP);        Activity.handledecode (Result) message.obj, barcode);  Break;  Caser.id.decode_failed://We ' re decoding as fast as possible, so when one decode fails, start another.State =State.preview;        Cameramanager.get (). Requestpreviewframe (Decodethread.gethandler (), R.id.decode);  Break;  Caser.id.return_scan_result:log.d (TAG,"Got return scan result message");        Activity.setresult (ACTIVITY.RESULT_OK, (Intent) message.obj);        Activity.finish ();  Break;  Caser.id.launch_product_query:log.d (TAG,"Got Product Query Message"); String URL=(String) message.obj; Intent Intent=NewIntent (Intent.action_view, Uri.parse (URL));        Intent.addflags (Intent.flag_activity_clear_when_task_reset);        Activity.startactivity (Intent);  Break; }  }

Above is the decoding of the thread processing different states need to pay attention to the place, we here only to see the success of the image capture, the successful capture of the image decoding the real decodethread inside implementation, Decodethread inside the decoding success, will be serialized data, and then saved to the bundle inside , we can get the image data directly through the serialization of the bundle. At the same time, the decoded results will be stored in the MSG, and then can be processed according to the actual situation, such as the above code, after the successful decoding, will call a processing function:

//edited by Mythou//http://www.cnblogs.com/mythou/     Public voidHandledecode (FinalResult obj, Bitmap barcode)        {inactivitytimer.onactivity ();        Playbeepsoundandvibrate (); Alertdialog.builder Dialog=NewAlertdialog.builder ( This); if(Barcode = =NULL) {Dialog.seticon (NULL); }        Else{drawable drawable=Newbitmapdrawable (barcode);        Dialog.seticon (drawable); } dialog.settitle ("Scan Results");        Dialog.setmessage (Obj.gettext ()); Dialog.setnegativebutton ("OK",NewDialoginterface.onclicklistener () {@Override Public voidOnClick (Dialoginterface Dialog,intwhich) {                //Open the scanned address with the default browserIntent Intent =NewIntent (); Intent.setaction ("Android.intent.action.VIEW"); Uri Content_url=Uri.parse (Obj.gettext ());                Intent.setdata (Content_url);                StartActivity (Intent);            Finish ();        }        }); Dialog.setpositivebutton ("Cancel",NewDialoginterface.onclicklistener () {@Override Public voidOnClick (Dialoginterface Dialog,intwhich)            {Finish ();        }        });    Dialog.create (). Show (); }

Above is the entire QR code decoding process, which involves a lot of camera use, so if you need to use two-dimensional code recognition, you need to note that your program needs to apply for the following permissions, general camera use and camera autofocus and so on.

// edited by Mythou // http://www.cnblogs.com/mythou/<uses-permission android:name= "Android.permission.CAMERA" ></ Uses-permission><uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE" ></ Uses-permission><uses-feature android:name= "Android.hardware.camera"/><uses-feature android:name= " Android.hardware.camera.autofocus "/>

5, the conclusion above is to generate and identify two-dimensional code of the key process and code, interested friends can view the source of zxing, there is a lot of knowledge of image analysis can learn. Specific use can also refer to the demo I gave below. QR code for mobile development is a very common technology, so there is a time to understand, maybe when the use of. In addition, zxing library in addition to the two-dimensional code, in fact, for the bar code is also supported, but I do not introduce here. You need to see the source code.
zxing Open Source project Google Code address:https://code.google.com/p/zxing/ zxingdemo Download: <ignore_js_op> zxingdemo2013-8-25.rar (426.46 KB, download count: 1111)

2013-8-30 14:59 Upload Click file name to download attachments
Download points: Download Beans-2

Android QR code generation and identification (with demo source)

Related Article

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.