Android based on Google zxing implementation of QR code generation, recognition and long-press recognition of the effect

Source: Internet
Author: User

The recent project used to the generation and identification of two-dimensional code, before touching this piece, and then on the Internet search, found that there are many resources in this area, in particular, Google zxing to the two-dimensional code package, the implementation has been good, can directly take over the reference, downloaded their source code, only made a few changes, It is in the demo to add a long-press recognition function, although the internet has long-press recognition of the demo, but a lot of download down but can not run, and then summed up a bit, added in the following demo.



, refer to the package in red is placed in the corresponding folder of your project, of course, some resource files, such as the reference to the project in the string.xml you add it is of course don't forget to put the rack bag


Here's a description of the main class of the demo

public class Barcodetestactivity extends Activity {private TextView resulttextview;private EditText Qrstredittext;priva    Te ImageView qrimgimageview;private String time;     Private file File = null;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                Setcontentview (R.layout.main);        Resulttextview = (TextView) This.findviewbyid (R.id.tv_scan_result);        Qrstredittext = (EditText) This.findviewbyid (r.id.et_qr_string);                Qrimgimageview = (ImageView) This.findviewbyid (r.id.iv_qr_image);        Button Scanbarcodebutton = (button) This.findviewbyid (R.id.btn_scan_barcode); Scanbarcodebutton.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {// Open Scan Interface Scan barcode or QR code Intent opencameraintent = new Intent (barcodetestactivity.this,captureactivity.class);                Startactivityforresult (opencameraintent, 0);}); Qrimgimageview.setonlongclicklistener (New OnlongclicklisteneR () {@Overridepublic Boolean onlongclick (View v) {//long press recognizes QR code savecurrentimage (); return true;}});        Button Generateqrcodebutton = (button) This.findviewbyid (R.id.btn_add_qrcode); Generateqrcodebutton.setonclicklistener (New Onclicklistener () {@Overridepublic void OnClick (View v) {try {String contentstring = Qrstredittext.gettext (). toString (), if (!contentstring.equals ("")) {//Generate two-dimensional code images from a string and display them on the interface, The second parameter is the size of the picture (350*350) Bitmap qrcodebitmap = Encodinghandler.createqrcode (contentstring, 350); Qrimgimageview.setimagebitmap (QRCODEBITMAP);} else {//hint text cannot be empty toast.maketext (barcodetestactivity.this, "text can is not is empty", Toast.length_short). Show ();}}    catch (Writerexception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}); }//This method status bar is blank and does not display the information of the status bar private void Savecurrentimage () {//Gets the current screen size int width = GetWindow (). GE        Tdecorview (). Getrootview (). GetWidth (); int height = GetWindow (). Getdecorview (). Getrootview (). GetheiGht ();        Generate images of the same size Bitmap Tembitmap = bitmap.createbitmap (width, height, Bitmap.Config.ARGB_8888);        Locate the root layout of the current page view view = GetWindow (). Getdecorview (). Getrootview ();        Set Cache view.setdrawingcacheenabled (TRUE);        View.builddrawingcache ();        Get the picture of the current screen from the cache and create a copy of the Drawingcache, because Drawingcache gets a bitmap that is recycled Tembitmap = View.getdrawingcache () when it is disabled;        SimpleDateFormat df = new SimpleDateFormat ("Yyyymmddhhmmss");        Time = Df.format (new Date ()); if (Environment.MEDIA_MOUNTED.equals (Environment.getexternalstoragestate ())) {file = new file (environment.getext            Ernalstoragedirectory (). GetAbsolutePath () + "/screen", Time + ". png");                if (!file.exists ()) {File.getparentfile (). Mkdirs ();                try {file.createnewfile ();                } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();     }       } FileOutputStream fos = null;                try {fos = new FileOutputStream (file);                Tembitmap.compress (Bitmap.CompressFormat.PNG, N, FOS);                Fos.flush ();            Fos.close ();            } catch (FileNotFoundException e) {e.printstacktrace ();            } catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();                    } New Thread (new Runnable () {@Override public void run () {                    String path = Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/screen/" + Time + ". png";                    Final result = Parseqrcodebitmap (path);                        Runonuithread (New Runnable () {public void run () {if (Null!=result) {                        Resulttextview.settext (Result.tostring ());                     }else{       Toast.maketext (Barcodetestactivity.this, "unrecognized", Toast.length_long). Show ();                }                        }                    });            }}). Start ();        Disabling DRAWINGCAHCE otherwise affects performance, and does not prohibit a bitmap view.setdrawingcacheenabled (false) that causes the cache to be saved each time. }}//Parse the QR code image and return the result encapsulated in the result object private Com.google.zxing.Result parseqrcodebitmap (String bi Tmappath) {//Resolution conversion type UTF-8 Hashtable<decodehinttype, string> hints = new Hashtable<decodehinttype          , string> ();          Hints.put (Decodehinttype.character_set, "utf-8");           Get to the image to be parsed bitmapfactory.options Options = new Bitmapfactory.options (); If we set Injustdecodebounds to True, then Bitmapfactory.decodefile (String path, Options opt)//will not really return a bitmap to you, it will simply put its width          , high fetch back to you options.injustdecodebounds = true; At this point the Bitmap is null, and after this code, Options.outwidth and Options.outheight are the width and height of the Bitmap bi we want.TMap = Bitmapfactory.decodefile (bitmappath,options);             We now want to take out the picture of the side length (QR code picture is square) set to 400 pixels/** options.outheight = 400;             Options.outwidth = 400;             Options.injustdecodebounds = false;         Bitmap = Bitmapfactory.decodefile (Bitmappath, Options); */////////above this practice, although the bitmap limit to the size we want, but did not save memory, if we want to save memory, we also need to use insimplesize this property options.insamplesize = Options          . outheight/400; if (options.insamplesize <= 0) {options.insamplesize = 1;//prevent its value less than or equal to 0}/** * Secondary    Help save Memory Settings * * Options.inpreferredconfig = Bitmap.Config.ARGB_4444;           The default is Bitmap.Config.ARGB_8888 * options.inpurgeable = true;           * Options.ininputshareable = true;          */options.injustdecodebounds = false;           Bitmap = Bitmapfactory.decodefile (Bitmappath, Options); Create a new Rgbluminancesource object and pass the bitmap picture to this object Rgbluminancesource RgbluminancesourCE = new Rgbluminancesource (bitmap);          Convert picture to binary picture binarybitmap Binarybitmap = new Binarybitmap (new Hybridbinarizer (Rgbluminancesource));          Initialize Parse object Qrcodereader reader = new Qrcodereader ();          Start parsing result = null;          try {result = Reader.decode (Binarybitmap, hints);      } catch (Exception e) {//Todo:handle Exception} return result; } @Overrideprotected void Onactivityresult (int requestcode, int resultcode, Intent data) {Super.onactivityresult (reques Tcode, ResultCode, data);//processing the scan result (shown on the interface) if (ResultCode = = RESULT_OK) {Bundle bundle = Data.getextras (); String Scanresult = bundle.getstring ("result"); Resulttextview.settext (Scanresult);}}


And then long press recognize QR code called Rgbluminancesource This class

public class Rgbluminancesource extends Luminancesource {private byte bitmappixels[];p rotected Rgbluminancesource ( Bitmap Bitmap) {super (Bitmap.getwidth (), Bitmap.getheight ());//First, to get the image of the pixel array content int[] data = new Int[bitmap.getwidth () * Bitmap.getheight ()];this.bitmappixels = new Byte[bitmap.getwidth () * Bitmap.getheight ()];bitmap.getpixels (data, 0, GetWidth (), 0, 0, getwidth (), getheight ());//convert int array to byte array, that is, take the blue value part of the pixel value as the discrimination content for (int i = 0; i < data.length; i++) {This.bitmappixels[i] = (byte) data[i];}} @Overridepublic byte[] Getmatrix () {//Return our generated good pixel data return bitmappixels;} @Overridepublic byte[] GetRow (int y, byte[] row) {//here to get the pixel data for the specified row system.arraycopy (bitmappixels, Y * getwidth (), row, 0, G Etwidth ()); return row;}} Camera recognition QR code called Captureactivity This class public class Captureactivity extends Activity implements Callback {private Captureactivityhandler handler;private viewfinderview viewfinderview;private boolean hassurface;private Vector< barcodeformat> decodeformats;private String CharActerset;private Inactivitytimer inactivitytimer;private MediaPlayer mediaplayer;private boolean playbeep;private Static final Float Beep_volume = 0.10f;private Boolean vibrate;private Button cancelscanbutton;/** called when the Activit Y is first created. */@Overridepublic void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.camera); Cameramanager.init (Getapplication ()); Viewfinderview = (Viewfinderview) Findviewbyid (R.id.viewfinder_view); Cancelscanbutton = (Button) This.findviewbyid (r.id.btn_cancel_scan); hassurface = False;inactivitytimer = new Inactivitytimer (this);} @Overrideprotected void Onresume () {super.onresume (); Surfaceview Surfaceview = (surfaceview) Findviewbyid (R.id.preview_view); Surfaceholder Surfaceholder = Surfaceview.getholder (); if (hassurface) {Initcamera (surfaceholder);} else { Surfaceholder.addcallback (this); Surfaceholder.settype (surfaceholder.surface_type_push_buffers);} Decodeformats = Null;characterset = Null;playbeep = tRue Audiomanager Audioservice = (audiomanager) getsystemservice (Audio_service); if (Audioservice.getringermode ()! = Audiomanager.ringer_mode_normal) {playbeep = false;} Initbeepsound (); vibrate = True;//quit the scan Viewcancelscanbutton.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {CaptureActivity.this.finish ();}}); @Overrideprotected void OnPause () {super.onpause (); if (handler! = null) {handler.quitsynchronously (); handler = null;} Cameramanager.get (). Closedriver ();} @Overrideprotected void OnDestroy () {inactivitytimer.shutdown (); Super.ondestroy ();} /*** Handler Scan result* @param result* @param barcode*/public void Handledecode (result result, Bitmap barcode) {Inactivi Tytimer.onactivity ();p laybeepsoundandvibrate (); String resultstring = Result.gettext ();//fixmeif (Resultstring.equals ("")) {//scan failed Toast.maketext ( Captureactivity.this, "Scan failed!", Toast.length_short). Show (); else {//System.out.println ("Result:" +resultstring); Intent resultintent = new IntenT (); Bundle bundle = new bundle (); Bundle.putstring ("Result", resultstring); Resultintent.putextras (bundle); This.setresult (RESULT_OK, resultintent);} CaptureActivity.this.finish ();} private void Initcamera (Surfaceholder surfaceholder) {try {cameramanager.get (). Opendriver (Surfaceholder);} catch ( IOException IoE) {return;} catch (RuntimeException e) {return;} if (handler = = null) {handler = new Captureactivityhandler (this, decodeformats,characterset);}} @Overridepublic void Surfacechanged (surfaceholder holder, int format, int width,int height) {} @Overridepublic void Surfac Ecreated (Surfaceholder holder) {if (!hassurface) {hassurface = True;initcamera (holder);}} @Overridepublic void surfacedestroyed (Surfaceholder holder) {hassurface = false;} Public Viewfinderview Getviewfinderview () {return viewfinderview;} Public Handler GetHandler () {return Handler;} public void Drawviewfinder () {Viewfinderview.drawviewfinder ();} private void Initbeepsound () {if (playbeep && mediaPlayer = = null) {//The VolUme on Stream_system isn't adjustable, and users found it//too loud,//so we are play on the music stream.setvolumecontr Olstream (audiomanager.stream_music); mediaPlayer = new MediaPlayer (); Mediaplayer.setaudiostreamtype ( Audiomanager.stream_music); Mediaplayer.setoncompletionlistener (Beeplistener); Assetfiledescriptor file = Getresources (). OPENRAWRESOURCEFD (r.raw.beep); try {Mediaplayer.setdatasource ( File.getfiledescriptor (), File.getstartoffset (), file.getlength ()); File.close (); Mediaplayer.setvolume (BEEP_ VOLUME, Beep_volume); Mediaplayer.prepare ();} catch (IOException e) {mediaPlayer = null;}}} Private static final Long vibrate_duration = 200l;private void Playbeepsoundandvibrate () {if (Playbeep && Mediapla Yer! = null) {Mediaplayer.start ();} if (vibrate) {Vibrator Vibrator = (Vibrator) getsystemservice (Vibrator_service); vibrator.vibrate (VIBRATE_DURATION);}} /*** when the Beep have finished playing, rewind to queue up another one.*/private final Oncompletionlistener Beeplistener = new ONcompletionlistener () {public void oncompletion (MediaPlayer MediaPlayer) {mediaplayer.seekto (0);}};} 


Here is the main layout mian file

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:background=" @android: Colo R/white "android:orientation=" vertical "> <button android:id=" @+id/btn_scan_barcode "Android:lay Out_width= "Fill_parent" android:layout_height= "wrap_content" android:layout_margintop= "30DP" Android: text= "Open camera"/> <linearlayout android:orientation= "Horizontal" android:layout_margintop= "10DP" android:layout_width= "fill_parent" android:layout_height= "wrap_content" > <textvi EW android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:textcolor= "@andr         Oid:color/black "android:textsize=" 18sp "android:text=" Scan Result: "/> <textview Android:id= "@+id/tv_scan_result"        Android:layout_width= "Fill_parent" android:textsize= "18sp" android:textcolor= "@android: Color/black" android:layout_height= "Wrap_content"/> </LinearLayout> <edittext android:id= "@+id/et _qr_string "android:layout_width=" fill_parent "android:layout_height=" Wrap_content "Android:layout_ma        rgintop= "30DP" android:hint= "Input the text"/> <button android:id= "@+id/btn_add_qrcode"         Android:layout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "Generate QRcode"/> <imageview android:id= "@+id/iv_qr_image" android:layout_width= "250DP" Android:layout_heig ht= "250DP" android:scaletype= "Fitxy" android:layout_margintop= "10DP" android:layout_gravity= "center"/ ></LinearLayout>


For more information, please download the demo yourself, the demo solves the phenomenon of the two-dimensional code being stretched when the vertical beat is decoded.

But I encountered a problem is two-dimensional Code scan box after the size of the scan to reduce the sensitivity, want to know the guidance of friends

Interested can download demo to have a look

http://download.csdn.net/detail/shihuiyun/9537714

Android based on Google zxing implementation of QR code generation, recognition and long-press recognition of the effect

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.