Two-dimensional code generation and scanning in Android

Source: Internet
Author: User

Reprint please indicate the source:
http://blog.csdn.net/hai_qing_xu_kong/article/details/51260428
This article is from: "Gu Linhai's Blog"

Objective

Leave the company at the end of the month, ready to rest at the end of a period of time, before every day busy work, and even some interesting things have not been studied, while this time can enjoy, today this article mainly describes the generation and scanning of two-dimensional code, using the current popular zxing, The bottom will give the entire project GitHub address, why to speak two-dimensional code, because the QR code is too common, any app will have a QR code scan.

Zxing use

After downloading the project from the bottom GitHub project, you can see the overall code structure as follows:

We simply copy all the code under the Zxing package to our project, in addition to this code, we also need to zxing the jar package, and copy a copy from the project directly

After all the copy is complete, the corresponding resource file is also required

1. The IDs file under the values file
2. resource files in raw files (can be replaced)
3, layout files under the Activity_capture.xml (you can make the corresponding custom)
4. Picture Resources

Generate two-dimensional code

After the above work is all ready, you can create our QR code, how to generate two-dimensional code? You need to encodingutils this QR code generation tool class. Generate a QR code by invoking the Createqrcode method in the tool class.

publicstaticcreateQRCodeintint heightPix, Bitmap logoBm)

The Createqrcode method parameters are as follows:

Content: Two-dimensional code contents
Widthpix: Two-dimensional code width
Heightpix: Two-dimensional code height
LOGOBM: Two-dimensional code in the middle of the logo

    /** * Create a QR code and save the picture locally */    Private void Create() {intwidth = densityutil.dip2px ( This, $); Bitmap Bitmap = Encodingutils.createqrcode ("Http://www.baidu.com", width, width, bitmapfactory.decoderesource (getresources (), R.drawable.ic_launcher)        );        Iv_zxing.setimagebitmap (bitmap);    Savebitmap (bitmap); }/** * Save Bitmap in local * * @param bitmap */     Public void Savebitmap(Bitmap Bitmap) {//Save the picture firstFile Appdir =NewFile (Environment.getexternalstoragedirectory (),"Zxing_image");if(!appdir.exists ())        {Appdir.mkdir (); } String FileName ="Zxing_image"+". jpg"; File File =NewFile (Appdir, fileName);Try{FileOutputStream FOS =NewFileOutputStream (file); Bitmap.compress (Compressformat.jpeg, -, FOS);            Fos.flush ();        Fos.close (); }Catch(FileNotFoundException e)        {E.printstacktrace (); }Catch(IOException e)        {E.printstacktrace (); }//Insert files into the System Gallery        Try{MediaStore.Images.Media.insertImage ( This. Getcontentresolver (), File.getabsolutepath (), FileName,NULL); }Catch(FileNotFoundException e)        {E.printstacktrace (); }//Notification Gallery UpdateSendbroadcast (NewIntent (Intent.action_media_scanner_scan_file, Uri.parse ("file://"+"/sdcard/namecard/"))); }

The generated two-dimensional code content is a Baidu address, the middle logo is the default Android small robot.

Run the program to see the following effects:

Two-dimensional code scanning

QR code scanning need to use our captureactivity this class, open the Captureactivity interface and Scan, after the scan completed callback Onactivityresult method, That is, we can get the results after scanning through onactivityresult. The detailed code is as follows:

    /** * Open QR Code scan * /    Private void Open() {config (); Startactivityforresult (NewIntent (mainactivity. This, Captureactivity.class),0); }/** * Improve screen brightness * /    Private void Config() {Windowmanager.layoutparams LP = GetWindow (). GetAttributes (); Lp.screenbrightness =1.0F    GetWindow (). SetAttributes (LP); }@Override    protected void Onactivityresult(intRequestcode,intResultCode, Intent data) {Super. Onactivityresult (Requestcode, ResultCode, data);if(ResultCode = = RESULT_OK)            {Bundle bundle = Data.getextras (); String result = bundle.getstring ("Result");        Tv_result.settext (result); }    }

The effect is not demonstrated, because the simulator is used.

Scan Local Pictures

Scanning local images requires us to make the appropriate changes in captureactivity, so I added a button at the bottom of the scan interface to select Local images. The layout code is not shown here, we look directly at the post-click event handling.

    /**     * 打开本地图片     */    privatevoidopenLocalImage() {        // 打开手机中的相册        new Intent(Intent.ACTION_GET_CONTENT);         innerIntent.setType("image/*");        "选择二维码图片");        this0x01);    }

When you open the System picture library and select the picture, you need to override the Onactivityresult method to return the picture information.

    @Override    protected void Onactivityresult(intRequestcode,intResultCode, Intent data) {Super. Onactivityresult (Requestcode, ResultCode, data);if(ResultCode = = RESULT_OK) {Switch(Requestcode) { Case 0x01://Get the path to the selected picturecursor cursor = getcontentresolver (). Query (Data.getdata (),NULL,NULL,NULL,NULL);if(Cursor.movetofirst ()) {Photo_path = cursor.getstring (cursor. Getcolumnindex (MediaStore.Images.Med Ia.                DATA)); } cursor.close ();NewThread (NewRunnable () {@Override                     Public void Run() {Result result = Scanningimage (Photo_path);if(Result! =NULL) {Handledecode (result,NewBundle ()); }}). Start (); Break; }        }    }

After obtaining the picture path Photo_path, call the Scanningimage method to scan, zxing source, the results are stored in the result set. After obtaining the result, the return of the results, read the captureactivity source code, you can know the final result of the Assembly passed to the Handledecode method.

    /** * A Valid barcode have been found, so give an indication of success and show * the results.     * * @param Rawresult * The contents of the barcode. * @param Bundle * The extras * *     Public void Handledecode(Result Rawresult, bundle bundle)        {inactivitytimer.onactivity ();        Beepmanager.playbeepsoundandvibrate (); Intent resultintent =NewIntent (); Bundle.putint ("width", Mcroprect.width ()); Bundle.putint ("Height", Mcroprect.height ()); Bundle.putstring ("Result", Rawresult.gettext ()); Resultintent.putextras (bundle); This. Setresult (RESULT_OK, resultintent); Captureactivity. This. Finish (); }

After getting to the picture path, you need to wrap the QR code information into the result object, so you need to parse the picture:

    /** * How to scan a QR code image * * @param path * @return  * *     PublicResultScanningimage(String Path) {if(Textutils.isempty (path)) {return NULL; } hashtable<decodehinttype, string> hints =NewHashtable<decodehinttype, string> (); Hints.put (Decodehinttype.character_set,"UTF8");//Set coding of QR code contentBitmapfactory.options Options =NewBitmapfactory.options (); Options.injustdecodebounds =true;//Get original size firstScanbitmap = bitmapfactory.decodefile (path, options); Options.injustdecodebounds =false;//Get new size        intSampleSize = (int) (Options.outheight/(float) $);if(SampleSize <=0) SampleSize =1;        Options.insamplesize = samplesize; Scanbitmap = bitmapfactory.decodefile (path, options);intwidth = Scanbitmap.getwidth ();intHeight = scanbitmap.getheight ();int[] pixels =New int[Width * height]; Scanbitmap.getpixels (Pixels,0, Width,0,0, width, height);/** * The third parameter is the pixel of the picture */Rgbluminancesource Source =NewRgbluminancesource (width, height, pixels); Binarybitmap Bitmap1 =NewBinarybitmap (NewHybridbinarizer (source)); Qrcodereader reader =NewQrcodereader ();Try{returnReader.decode (Bitmap1, hints); }Catch(Notfoundexception e)        {E.printstacktrace (); }Catch(Checksumexception e)        {E.printstacktrace (); }Catch(FormatException e)        {E.printstacktrace (); }return NULL; }

The bitmap is obtained according to the path, and finally is parsed into the result object by the Decode method in the Qrcodereader and returned, and finally passed to the Handledecode method.

The effect of running the program is as follows:

The last scan came out of the previously defined Baidu address.

Permissions and Activity

When the QR code is generated and scanned, do not forget the permissions:

<?xml version= "1.0" encoding= "Utf-8"?><manifest xmlns:android="Http://schemas.android.com/apk/res/android"  package ="Com.example.zxingtest"android:versioncode="1"android:versionname ="1.0" >                <uses-permission android:name="Android.permission.WRITE_EXTERNAL_STORAGE" />    <uses-permission android:name="Android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />    <uses-permission android:name="Android.permission.CAMERA"/>    <uses-permission android:name="Android.permission.VIBRATE"/>    <uses-sdkandroid:minsdkversion="android:targetsdkversion" = "/>"                     <applicationandroid:allowbackup="true"android:icon="@drawable/ Ic_launcher "android:label=" @string/app_name "android:theme=" @style/apptheme " >                                        <activityandroid:name=". Mainactivity "android:label=" @string/app_name " >                                    <intent-filter>                <action android:name="Android.intent.action.MAIN" />                <category android:name="Android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <activity android:name="com.example.zxingtest.zxing.activity.CaptureActivity "></activity>    </Application></manifest>

The following is the full GitHub project address
GitHub Project Source Address: Click "Project Source Code"

Two-dimensional code generation and scanning in Android

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.