"Turn" Android QR code generation and identification (with demo source)--good

Source: Internet
Author: User
Tags image processing library

Original URL: http://www.cnblogs.com/mythou/p/3280023.html

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. (PS: New QQ Group, interested can join together to discuss: Android Group: 322599434) 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 code

The 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/
//address or string to be converted, can be in Chinesepublic void createqrimage (String url) {try {//Judge URL legalityif (url = = NULL | | ". Equals (URL) | |            Url.length () < 1) {return;            } hashtable<encodehinttype, string> hints = new Hashtable<encodehinttype, string> (); Hints.put (Encodehinttype.character_set, "utf-8");//image data conversion, using matrix conversionBitmatrix Bitmatrix = new Qrcodewriter (). Encode (URL, Barcodeformat.qr_code, qr_width, qr_height, hints); int[] pixels = new int[qr_width * Qr_height];//Below here according to the two-dimensional code algorithm, one by one to generate a picture of two-dimensional code,///Two for loop is the result of the picture Heng Lie scanfor (int y = 0, y < qr_height; y++) {for (int x = 0; x < qr_width; + +) { if (Bitmatrix.get (x, y)) {Pixels[y * qr_width + x] = 0xff000                    000;                    } else {Pixels[y * qr_width + x] = 0xFFFFFFFF; }                }            }//Generate QR Code image format, use 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);//Show to a ImageView aboveSweepiv.setimagebitmap (bitmap);        } catch (Writerexception e) {e.printstacktrace (); }    }

The above is the two-dimensional code generation method interface, if you are only the user method, very simple, just pass in a URL, just like in my inside, passed to a legitimate URL. 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 for information

Scanning to obtain QR code information is slightly more complicated, mainly need to write the use of the camera, this is the same as we generally use the camera, we need to use Surfaceview as a preview, this one I do not 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      = State.preview;      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 void Handlemessage (message message) {switch (message.what) {case r.id.auto_focus://log.d (TAG, "Go        T 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;        Case R.ID.RESTART_PREVIEW:LOG.D (TAG, "Got restart Preview message");        Restartpreviewanddecode ();      Break Case r.id.decode_succeeded:
     //Decoding succeeds, obtains the result of the interface and the original QR code data LOG.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 Case r.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 Case R.ID.RETURN_SCAN_RESULT:LOG.D (TAG, "Got return scan result message"); Activity.setresult (ACTIVITY.RESULT_OK, (Intent) message.obj); Activity.finish (); Break Case R.ID.LAUNCH_PRODUCT_QUERY:LOG.D (TAG, "Got product Query Message"); String url = (string) message.obj; Intent Intent = new Intent (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 void Handledecode (final Result obj, Bitmap barcode) {inactivitytimer.onactivity ();        Playbeepsoundandvibrate ();        Alertdialog.builder dialog = new Alertdialog.builder (this);        if (barcode = = null) {Dialog.seticon (null);            } else {drawable drawable = new bitmapdrawable (barcode);        Dialog.seticon (drawable);        } dialog.settitle ("Scan results");        Dialog.setmessage (Obj.gettext ()); Dialog.setnegativebutton ("OK", new Dialoginterface.onclicklistener () {@Override public void OnClick (dialoginterface dialog, int which) {//Open the scanned address with the default browser Intent Intent = NE                W Intent ();                Intent.setaction ("Android.intent.action.VIEW");                Uri Content_url = Uri.parse (Obj.gettext ());                Intent.setdata (Content_url);                StartActivity (Intent);            Finish ();  }        });      Dialog.setpositivebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public            void OnClick (Dialoginterface dialog, int which) {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. Conclusion

The above is the generation and identification of the key process and code of QR codes, 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.

2013-8-16

Edited by Bubble gum

Zxing Open Source project Google code address: https://code.google.com/p/zxing/

Zxingdemo Download: Zxingdemo2013-8-25.rar

Edited by Mythou

Original post, reprint please indicate source: http://www.cnblogs.com/mythou/p/3280023.html

"Turn" Android QR code generation and identification (with demo source)--good

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.