Today we are going to talk about the most commonly used technology in mobile field--two-dimensional code. Now the streets, major sites have two-dimensional code traces, whether it is iOS, Android, WP has related support software. Before I wanted to know how the two-dimensional code is working, recently because the work needs to use the relevant technology, so do a preliminary understanding. Today is mainly about how to use the Zxing library to generate and identify two-dimensional code. This article is mainly practical, theoretical will not explain too much, have the interest to see the source.
1, zxing Library Introduction
Here is a brief introduction to the Zxing library. Zxing is an open source, Java-implemented 1d/2d barcode image processing library, which contains ports that are contacted in other languages. Zxing can achieve the use of mobile phone's built-in camera to complete the barcode scanning and decoding. The project can be implemented by barcode coding 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 open source class library, previously on the function machine, there are developers using J2ME to use the zxing, but to support the JSR-234 specification (AF) mobile phone can play its power.
The following is Zxing demo run, I created a two-dimensional code here, we can use micro-letter sweep function, try. You can simply open the URL below.
2, zxing Library main class
Here are some of the main classes in the Zxing library and the role of these classes:
Captureactivity. This is the starting activity, which is the scanner.
Captureactivityhandler decoding processing class, is responsible for calling another thread to decode.
Decodethread the decoded thread.
Com.google.zxing.client.android.camera bag, Camera control pack.
Viewfinderview's Custom view is the box in the middle of the shot we saw.
3, using zxing to generate two-dimensional code
The following for two-dimensional code generation and resolution to do a simple introduction, as for the detailed use of methods, we suggest that we still look at the source code, use it is very simple, but this open source project, it is worth a good look. First, a two-dimensional code generation method is given:
The address or string to be converted, can be Chinese public void createqrimage (string url) {try {//Judge URL legality if (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 conversion Bitmatrix Bitmatrix = new Qrcodewriter (). 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, the image of two-dimensional code generation,///Two for loop is the result of the picture row scan for (int y = 0; y < qr_height; y++) {for (int x = 0; x < Qr_wid TH;
X + +) {if (Bitmatrix.get (x, y)) {Pixels[y * qr_width + x] = 0xff000000;
else {Pixels[y * qr_width + x] = 0xFFFFFFFF;
}///Generate two-dimensional code picture format, using argb_8888 Bitmap 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 above Sweepiv.setimagebitmap (bitmap); catch (WriterexcEption e) {e.printstacktrace ();
}
}
The above is the two-dimensional code generation method interface, if you are just the user method, very simple, as long as the introduction of a URL can be, like my screenshot inside, a legitimate URL can be passed in. Or, as with some mobile apps now, the app download address can be turned into a two-dimensional code, so just scan it and download the app. This is also the current more popular app promotion way.
The above code does not do much, the main is to call Zxing library inside Qrcodewriter (). Encode the way we pass in the URL to encode, the specific how to encode, this I do not say in detail here, interested can see zxing source code. The end of the article will give the zxing source code and example codes.
4, scanning two-dimensional code to obtain information
Scanning to get two-dimensional code information is a little more complicated, mainly need to write camera use, this is the same as we generally use camera, need to use Surfaceview as a preview, this one I do not say, this should not be too complicated. It should be easy for a friend who has used camera to do a preview. The key process to get two-dimensional code data is to call the Zxing decoding interface in the camera of the AF callback function.
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 to say a little more, because the decoding needs a certain time, so zxing decoding calls, are used handler as a thread communication mechanism, decoding the work is placed in the independent thread, if you directly in the main thread decoding, I am afraid ANR problem is not to avoid.
public void handlemessage {switch (message.what) {case r.id.auto_focus://log.d (TAG, "Got AUTO-FOCU
S message "); When one of auto focus pass finishes, start another. This is the closest thing to//continuous AF.
It does seem to hunt a bit, but I ' m not sure what else todo.
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 success, get to the interface results and the original two-dimensional 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, then 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");
Activity.setresult (ACTIVITY.RESULT_OK, (Intent) message.obj);
Activity.finish ();
Break
Case R.ID.LAUNCH_PRODUCT_QUERY:LOG.D (TAG, "Got product query");
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 to handle different states when the need to pay attention to the place, we only look at the success of the image of the place, the successful acquisition of picture decoding really decodethread inside implementation, Decodethread inside the successful decoding, will be the data serialization, Then save it to the bundle, we can get the image data directly through the bundle serialization. At the same time, the decoded results will be saved into MSG, and then can be processed according to the actual situation, such as the above code, after the successful decoding, will call a handler function:
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 result");
Dialog.setmessage (Obj.gettext ()); Dialog.setnegativebutton (OK), new Dialoginterface.onclicklistener () {@Override public void OnClick (Dialoginterface D
Ialog, int which) {//Open scanned address with default browser Intent Intent = new 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 D
Ialog, int which) {finish ();
}
});
Dialog.create (). Show (); }
The above is the whole two-dimensional code decoding process, which involves a lot of camera use, so if you need to use two-dimensional code recognition, you need to pay attention to your program needs to apply for the following permissions, the general camera use and camera autofocus.
<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
Above is to generate and identify two-dimensional code of the key processes and code, interested friends can see the source of zxing, there are many image analysis of the knowledge can learn. Specific use can also refer to the demo I gave below. Two-dimensional code for the current mobile development is very common technology, so there is time to understand, maybe when the use of. In addition, zxing library in addition to two-dimensional code, in fact, the bar code is also supported, but I do not introduce here. Have the need to see the source code can be.
Zxing Open Source project Google code address: https://code.google.com/p/zxing/
Zxingdemo Download: Zxingdemo.rar
The above is the entire content of this article, I hope to give you a reference, but also hope that we support the cloud habitat community.