Android Project Combat (28): Using zxing to implement two-dimensional code and optimization examples _android

Source: Internet
Author: User
Tags gettext

Objective:

Years before the contact zxing to achieve two-dimensional code, did not expect today's project in the use of this is still zxing, Baidu, is such a cow's stuff.

Of course, in the project we may only use two-dimensional code scanning and generate two functions, so do not have to download the full jar package, the use of simplified version can be seen below.

This article describes:

1, if the rapid integration of zxing in the project, to achieve the scanning and generation of two-dimensional code functions

2, according to the project needs to modify the source code to achieve our requirements and optimize

One, fast integration zxing two-dimensional code

1, download the library file: Http://xiazai.jb51.net/201611/yuanma/ZXingBarCode_jb51.zip,

When the download is complete, you can see:

We need to copy these files into our own projects, starting with the following:

①, res directory: Raw folder entire copy to personal item relative position

②, res--> values directory: Ids.xml the contents of the file are all copied to the relative position of personal items, personal items do not directly copy files to the relative position

③, res--> values directory: Colors.xml the contents of a file are copied to the relative position of a personal item

④, res--> layout directory: Camera.xml layout file copied to personal project relative position

⑤, res--> drawable_mdpi directory: Navbar.9.png pictures copied to the relative position of the individual items, this picture is the title bar background picture, it is recommended to change the first navbar.png do not use. 9 pictures

⑥, libs directory: Zxing.jar files copied to the relative position of personal items, and right click As Library

⑦, src--> com directory: zxing folder copied to personal items relative position, will error, modify the directory structure of R can

⑧, Androidmanifest.xml file Add (two-dimensional code scan activity, which needs to be later to modify, to achieve their own requirements)

 <activity android:name= "Com.zxing.activity.CaptureActivity"/>

Add permissions in ⑨, androidmanifest.xml files

<uses-permission android:name= "Android.permission.CAMERA"/>
  <uses-permission android:name= " Android.permission.VIBRATE "/>
  <uses-permission android:name=" Android.permission.READ_EXTERNAL_STORAGE "/>
  <uses-permission android:name=" Android.permission.MOUNT_UNMOUNT_FILESYSTEMS "/>
< Uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

2, the preparation work is completed, the following start to write demo

Now the requirement is a main interface Mainactivity.java inside has two buttons, jump to generate two-dimensional code interface and scan two-dimensional code interface respectively
Then write the implementation of the two activity functions separately:

①, generate two-dimensional code

First write the layout file, a picture, a Start generation button, an input box (two-dimensional code needs to be generated according to text information, no text information can not be generated)
Activity_create.xml

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "xmlns:android=" Schemas.android.com/apk/res/android "xmlns:tools=" Http://schemas.android.com/tools "android:layout_width=" Match_ Parent "android:layout_height=" match_parent "android:orientation=" vertical "tools:context=" Com.maiji.zxingdemo.CreateActivity "> <imageview android:id=" @+id/create_img "android:layout_width=" 300DP 

  "Android:layout_height=" 300DP "android:scaletype=" Fitxy "android:layout_gravity=" Center_horizontal "/>" <button android:id= "@+id/create_btn" android:layout_width= wrap_content "android:layout_height=" Wrap_co Ntent "android:layout_gravity=" Center_horizontal "android:text=" starts to generate two-dimensional code "/> <edittext android:id= "@+id/create_edit" android:layout_width= "match_parent" android:layout_height= "wrap_content"/> </LinearLayou T> 

Activity code: The code is simpler and does not explain

Private ImageView create_img;
  Private Button create_btn;

  Private EditText Create_edit;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

    Setcontentview (r.layout.activity_create);
    Initview ();

  Initevent ();
  private void Initevent () {Create_btn.setonclicklistener (this);
    private void Initview () {create_img = (ImageView) Findviewbyid (r.id.create_img);
    CREATE_BTN = (Button) Findviewbyid (R.ID.CREATE_BTN);
  Create_edit = (edittext) Findviewbyid (R.id.create_edit); @Override public void OnClick (View v) {switch (V.getid ()) {Case r.id.create_btn:string content
        = "" ;
          if (Create_edit.gettext (). toString (). Equals ("")) {Toast.maketext (this, input two-dimensional code information, Toast.length_short). Show ();
        Return
        Content = Create_edit.gettext (). toString (); try {//Generate two-dimensional code picture, the first parameter is the content of two-dimensional code, the second parameter is the side length of the square picture, the unit is pixel Bitmap qrcodebitmAP = Encodinghandler.createqrcode (content, 800);
          if (qrcodebitmap!=null) {create_img.setimagebitmap (QRCODEBITMAP);
          }else{Toast.maketext (This, "generate a two-dimensional code failure", Toast.length_short). Show ();
        The catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
    } break;
    } public byte[] Bitmap2bytes (Bitmap BM) {Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
    Bm.compress (Bitmap.CompressFormat.PNG, BAOs);
  return Baos.tobytearray ();

 }

Effect Chart:

②, scanning two-dimensional code

This is simpler, just open a zxing-provided activity and get the scanned string.

See Key code for Scanactivity (scan activity)

Private TextView zxing_content;

@Override
protected void onCreate (Bundle savedinstancestate) {
  super.oncreate (savedinstancestate);
  Setcontentview (R.layout.activity_scan);
  Zxing_content = (TextView) Findviewbyid (r.id.zxing_content);
  Intent Startscan = new Intent (this,captureactivity.class);
  Startactivityforresult (Startscan, 0); Actually opened a zxing to provide us with the scanning activity, of course, we will later on the activity of some optimization modification

}

/**
 * Sweep, after the success of the return value to judge *
 *
Override public
void Onactivityresult (int requestcode, int resultcode, Intent data) {
  Super.onactivityresult (Requestcode, ResultCode, data);
  if (ResultCode = = 1) {
    String result = Data.getextras (). getString (' result ');
    Zxing_content.settext (result); Show scanned data from two-dimensional code
  }


Layout file:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android=
"http://schemas.android.com/apk" /res/android "
  xmlns:tools=" Http://schemas.android.com/tools "
  android:layout_width=" Match_parent
  " android:layout_height= "Match_parent"
  tools:context= "com.maiji.zxingdemo.ScanActivity" >

  <textview
    android:id= "@+id/zxing_content"
    android:layout_width= "wrap_content"
    android:layout_height= "WRAP_" Content "
    android:layout_centerinparent=" true "
    android:textsize=" 30sp "
    />
</ Relativelayout>

Effect Chart:

Second, the revision of the source code to achieve the needs of the project

1, modify the interface of two-dimensional code scanning

Corresponding to the Zxing-->activity-->captureactivity.java, the layout file is Camera.xml

So modifying the interface only needs to be modified in the Camera.xml file.

Nothing more than the original "Cancel" Cancel button removed, the top of the title bar change.

Inside the layout there is a <SurfaceView> control to display the camera Picture preview, which can be changed according to the requirements of the full interface display or display local

<com.zxing.view.ViewfinderView> control, that is, the scan box, the default is wide-height ratio of 1:1.5, the actual need to modify the width, described below

2. Modify the width and height of the scan frame

After the 1th step is done, we will find that we cannot modify the width of the scan box.

Modify Scan box width is simple, find Zxing-->camera-->cameramanager.java file

Here is the top of the code to see:

 private static final int min_frame_width =;
 private static final int min_frame_height =;
 private static final int max_frame_width =;
 private static final int max_frame_height = 480;

The value of these four properties, which is the width of the scan box, can then be modified directly according to the requirements, of course, this value in the different resolution of the device on the wide-high inconsistent, if necessary, you can do unit conversion

 public static int dp2px (context context,float DP) {
  final float scale = context.getresources (). Getdisplaymetrics (). D ensity;
  return (int) (DP * scale + 0.5f);
 }

Effect diagram: I have modified the minimum maximum width of the scan box to be consistent, and the "Cancel" button is deleted in the Camera.xml layout

3, to the scan box to add text tips

Look at the micro-letter scanning interface, you will find the scan box below a text hint. So we don't have this here, need to add

Find Zxing-->view-->viewfinderview.java

Here is the Custom Scan box class

Find code:

 Canvas.drawrect (Frame.left + 2, middle-1, frame.right-1, Middle + 2, paint);

   collection<resultpoint> currentpossible = possibleresultpoints;

In between these two lines of code, we draw a text hint

Canvas.drawrect (Frame.left + 2, middle-1, frame.right-1, Middle + 2, paint);
Textpaint textpaint = new Textpaint ();
   Textpaint.setargb (0xFF, 0xFF, 0xff,0xff);  Font Color
   textpaint.settextsize ();  Font size
   Textpaint.setantialias (TRUE);//Set anti-aliasing, otherwise the handwriting will be very fuzzy
   staticlayout layout = new Staticlayout ("Put the two-dimensional stacking into the box, Can be automatically scanned ", Textpaint,
       frame.right-frame.left, layout.alignment.align_normal,1.0f,0.0f,true);
   Canvas.translate (frame.left+5, (float) (Frame.bottom + (float) 30));   Draw the starting position
   Layout.draw (canvas);
collection<resultpoint> currentpossible = possibleresultpoints;

Then look at the scanning interface effect diagram:

4, solve the scanning interface Camera preview tensile deformation problem

Implementation of the above steps of optimization, careful students may find that if we give Surfaceview set Full-screen display (you can see a lot of camera screen), will find the camera shot out of the preview picture some stretch deformation

Reason: zxing horizontal screen after the vertical screen, camera code or the use of the horizontal screen code set parameters

Optimization method: Find zxing-->camera--> Cameraconfigurationmanager.java

Initfromcameraparameters method, in Log.d (TAG, "screen resolution:" + screenresolution); Add point after this sentence
Screenresolutionforcamera = new Point ();
screenresolutionforcamera.x = screenresolution.x;
SCREENRESOLUTIONFORCAMERA.Y = SCREENRESOLUTION.Y;
    
if (Screenresolution.x < SCREENRESOLUTION.Y) {
screenresolutionforcamera.x = SCREENRESOLUTION.Y;
SCREENRESOLUTIONFORCAMERA.Y = screenresolution.x;
 }

Again cameraresolution = getcameraresolution (parameters, screenresolution);

Cameraresolution = getcameraresolution (parameters, Screenresolutionforcamera);

After the completion of the scan operation, this time the camera shot out of the preview interface is normally displayed, no longer have the problem of stretching deformation.

This introduces a two-dimensional code module function that can be used for the project.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.