Android free walk into the zxing, easy to achieve QR code scanning

Source: Internet
Author: User
Tags decode all

Now many apps are integrated sweep sweep function, most commonly used, QQ, mobile assistant and so on. QR Code also makes life more concise, sweep the order, sweep the download and so on. So, speaking of QR code, we have to mention Google an open-source code-scanning framework: zxing.

Open Source Download: http://code.google.com/p/zxing/

Zxing is an open source library based on a variety of 1d/2d barcode processing and is a complete project. It can be used to scan and decode barcode by mobile phone camera, function and powerful. So if we want to realize the scanning and decoding of QR code, we need to simplify and modify it on the basis of this open source project. Let's take a look.

is modelled on the QQ sweep to modify the Zxing project, based on the Zxing project, the actual application, here made a three-point change:

(1) Vertical screen scanning

(2) Custom viewfinder

(3) Redefining scan result processing

First step: Download the Zxing project and simplify the scanning framework

1, first, download the latest zxing Open source project. : http://code.google.com/p/zxing/

2, analysis of project structure, clear scanning framework requirements. In zxing, there are many other functions, the project structure is more complex; for QR code qrcode scanning, we need several packages:

(1) Com.google.zxing.client.android.Camera based on Camera call and parameter configuration, core package

(2) Decodeformatmanager, Decodethread, Decodehandler decoding class based on decoding format, decoding thread, decoding result processing

(3) Viewfinderview, Viewfinderresultpointcallback view class defined based on viewfinder views

(4) Captureactivity, Captureactivityhandler capture class based on scan activity and scan result processing

(5) Inactivitytimer, Beepmanager, Finishlistener Auxiliary management class based on sleep, sound and exit

(6) Intents, Intentsource, Prefrencesactivity constant class based on constant storage

3, new project, add the following permissions:

  <uses-permission android:name= "Android.permission.CAMERA"/>         <uses-permission android:name= " Android.permission.INTERNET "/>         <uses-permission android:name=" Android.permission.VIBRATE "/>         <uses-permission android:name= "Android.permission.FLASHLIGHT"/>
Permission

Add Core.jar file and BuildPath; After adding the above class or package to the project, a series of errors will be reported for several reasons:

(1) Lack of resource files, copy the required resource files under Zxing to the new project

(2) version compatibility issues, zxing under a lot of technology are using 4.0 version and above, integrated into the lower version, the corresponding changes should be made, the details of reference project source code

(3) Package structure reference problem, need to re-import package reference

4, simplify capyureactivity, camera bag and decode all kinds of exception resolution, you can captureactivity code simplification, first look at the Capture.xml layout

 1 <merge xmlns:android= "http://schemas.android.com/apk/res/android" 2 xmlns:tools= "http://schemas.android.com/ Tools "> 3 4 <!--overall transparent canvas and 5 <surfaceview 6 android:id=" @+id/preview_view "7 Androi D:layout_width= "Fill_parent" 8 android:layout_height= "fill_parent"/> 9 <!--scan viewfinder-->11 <c Om.karics.library.zxing.view.ViewfinderView12 android:id= "@+id/viewfinder_view" android:layout_width= "fi         Ll_parent "android:layout_height=" Fill_parent "/>15 <!--title bar-->17 <relativelayout 18         Android:layout_width= "Fill_parent" android:layout_height= "50DP" android:layout_gravity= "top" 21 Android:background= "#99000000" >22 <imagebutton24 android:id= "@+id/capture_imag Eview_back "android:layout_width=" 42DP "android:layout_height=" 42DP "Android:lay Out_centervertical= "true" 28            android:background= "@drawable/selector_capture_back"/>29-<textview Roid:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_centerinp Arent= "true" android:textcolor= "#ffffffff" android:textsize= "20SP" android:text= "Sweep"/>37 </relativelayout>39 </merge>
Capture.xml

Capture.xml layout Removes the result display and adds a title bar. So captureactivity, OnCreate (), OnPause (), Onresume (), OnDestroy related to the initialization or destruction of the camera

 1 @Override 2 public void OnCreate (Bundle icicle) {3 super.oncreate (icicle); 4//Keep activity awake status 5 window window = GetWindow (); 6 window.addflags (WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); 7 Setcontentview (r.layout.capture); 8 9 Hassurface = false;10 Inactivitytimer = new Inactivitytimer (this); Beepmanager = new Bee Pmanager (this); imagebutton_back = (ImageButton) Findviewbyid (r.id.capture_imageview_back); Imagebu Tton_back.setonclicklistener (New View.onclicklistener () {@Override18 public void OnClick (Vie W v) {}21}),}23 @Override25 protected void Onresume ( ) {Super.onresume (); Cameramanager must be initialized here, not in OnCreate (). 29//This is necessary because we need to display the help page the first time we enter, we do not want to open the camera, measure the screen size 30//When the size of the scan box is incorrect, bug31 Cameramanager = new C Ameramanager (GetapplicatiOn ()); Viewfinderview = (Viewfinderview) Findviewbyid (R.id.viewfinder_view); viewfinderview.setcame Ramanager (cameramanager); handler = null;37, Surfaceview Surfaceview = (surfaceview) Findviewbyid (R             . Id.preview_view); Surfaceholder Surfaceholder = Surfaceview.getholder (); (hassurface) {41 The activity is paused but not stopped, so surface still exists; the surfacecreated () will not be called, so the Camera43 INITCA is initialized here Mera (surfaceholder); "Else {45//reset callback, wait for surfacecreated () to initialize Camera46 Surfacehold         Er.addcallback (this);}48 beepmanager.updateprefs (); Inactivitytimer.onresume (); 51 52      Source = intentsource.none;53 Decodeformats = null;54 CharacterSet = null;55}56 @Override58             protected void OnPause () {handler! = null) {handler.quitsynchronously (); 61       Handler = null;62  }63 inactivitytimer.onpause (); Beepmanager.close (); Cameramanager.closedriver () F (!hassurface) {Surfaceview Surfaceview = (surfaceview) Findviewbyid (R.id.preview_view);         Faceholder Surfaceholder = Surfaceview.getholder (); Surfaceholder.removecallback (this); 70}71         Super.onpause ();}73 @Override75 protected void OnDestroy () {Inactivitytimer.shutdown (); 77 Super.ondestroy (); 78}
View Code

Surfaceview is a camera-based implementation, the use of Surfaceview needs to implement the Surfaceholder.callback interface, when the screen is turned on surfaceview initialization of the camera

1 @Override 2 public     void surfacecreated (Surfaceholder holder) {3         if (!hassurface) {4             hassurface = true; 5
   initcamera (holder); 6         } 7     } 8  9     @Override10 public     void surfacedestroyed (Surfaceholder holder) {         Hassurface = false;12     }13     @Override15 public     void surfacechanged (surfaceholder holder, int format, int width,16< C14/>int height) {+     }
View Code

Next look at how to initialize the camera, following the code simplification

1 private void Initcamera (Surfaceholder surfaceholder) {2         if (Surfaceholder = = null) {3             throw new Illegalstateex Ception ("No Surfaceholder provided"); 4         } 5         if (Cameramanager.isopen ()) {6             return; 7         } 8         try {9             //Open camera Hardware Device             Cameramanager.opendriver (surfaceholder);             create a handler to open the preview and throw a run-time exception             (handler = = null)                 Handler = new Captureactivityhandler (this, decodeformats,14                         decodehints, CharacterSet, Cameramanager);             (         IOException IoE) {             LOG.W (TAG, IoE);             displayframeworkbugmessageandexit ();         catch (RuntimeException e) {             LOG.W (TAG, "Unexpected error initializing camera", e);             Displayframeworkbugmessageandexit ();         }23     }
View Code

In Captureactivity, there is a core method for returning and processing the decoded results, which is the result of the scan. Handledecode (), if it is necessary to do its own processing of the decoded content, the method needs to be changed, which is modified to the decoded bitmap and the content is uploaded to the activiity to open the scan for processing.

1 public void Handledecode (Result rawresult, Bitmap barcode, float scalefactor) {2         inactivitytimer.onactivity (); 3
   4         Boolean fromlivescan = barcode! = NULL; 5         //The result of the decoding is processed here, the parameter is passed back to activity processing 6         if (Fromlivescan) {7             beepmanager.playbeepsoundandvibrate (); 8  9             toast.maketext (this, "Scan succeeded", Toast.length_short). Show (); Ten             Intent Intent = Getintent ();             Intent.putextra ("Codedcontent", Rawresult.gettext ());             Intent.putextra ("Codedbitmap", barcode);             Setresult (RESULT_OK, intent);         }17 18     }
View Code

5. Generate two-dimensional code for the specified URL

 1/** 2 * Generate QRCode (QR code) 3 * 4 * @param STR 5 * @return 6 * @throws writerexception 7 */8  public static Bitmap createqrcode (String url) throws Writerexception {9 if (url = = NULL | | url.equals ("")) {One return null;12}13 14//Generate a two-dimensional matrix, specify the size of the encoding, do not generate a picture to be scaled later, which will blur the recognition failure of the Bitmatrix MA Trix = new Multiformatwriter (). Encode (url,16 Barcodeformat.qr_code, +); + int width = ma Trix.getwidth (); int height = matrix.getheight (); 20 21//two-dimensional matrix converted to one-dimensional array of pixels, that is, all the way across the line int[] pixels = new Int[width * height];23 for (int y = 0; y < height; y++) {(int x = 0; x < width;                 X + +) {matrix.get (x, y)) {pixels[y * width + x] = 0xff000000;28 }29}31}32 Bitmap Bitmap = Bitmap.createbitmap (width, height,34 bitm Ap. config.argb_8888); 35        Bitmap.setpixels (pixels, 0, width, 0, 0, width, height); return bitmap;37} 
View Code

Through the above four steps, the simplification of zxing project is basically completed. As for some classes need minor changes, hope can be carried out in the source code, here no longer repeat. The overall architecture of QR code scanning mainly consists of three parts:

1, define viewfinder, also be scanned view, draw through Surfaceview

2, camera, the core of the scan is the use of camera configuration, including preview, auto-focus, open equipment and other processing

3, decode decoding, scanning completed after the core of the project

In addition to the above three modules, it is necessary to be clear that captureactivitiy in the Handledecode () method to do their own processing.

Click on the link below to download the source code

Http://pan.baidu.com/s/1c0yADUS

Android free walk into the zxing, easy to achieve QR code scanning

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.