---
title: " 二维码、条形码扫描——使用Google ZXing"
author: "hack_zhang"
date: "2013-07-17T10:20:14Z"
tags: []
categories: ["移动开发"]
slug: "google-zxing"
draft: false
lastmod: "2013-07-17T10:20:14Z"
id: 1908224
url: "https://hack-zhang.iteye.com/blog/1908224"
---

我在项目中用到了二维码扫描的技术，用的是Google提供的ZXing开源项目，它提供二维码和条形码的扫描。扫描条形码就是直接读取条形码的内容，扫描二维码是按照自己指定的二维码格式进行编码和解码。

 

可以到[http://code.google.com/p/zxing/](http://code.google.com/p/zxing/)下载ZXing项目的源码，然后按照官方文档进行开发，我这里使用的ZXing是经过简化版的，去除了一些一般使用不必要的文件，项目工程截图如下：

 

![](http://my.csdn.net/uploads/201208/05/1344141694_2923.png)

 

其中encoding包是我 在它的基础上自己加上去的，功能是根据传入的字符串来生成二维码图片，返回一个Bitmap，其余的包是ZXing项目自带的。另外对扫描界面的布局我也 进行了修改，官方的扫描界面是横向的，我改成了纵向的，并加入了顶部的Tab和取消按钮（camera.xml），另外还需要的一些文件是 colors.xml、ids.xml，这些都是原本ZXing项目中自带的，最后就是libs下面的jar包。

 

 

先来看看最后的效果：

 

首先是根据输入的字符串生成二维码图片（左图），然后扫描二维码图片可以在界面上显示扫描结果（右图）：

 

 

             ![](http://my.csdn.net/uploads/201208/05/1344142596_7727.png)              ![](http://my.csdn.net/uploads/201208/05/1344142613_8189.png)

 

 

点击Open Camera按钮代开扫描框（左图），扫描条形码结果如下（右图）：

 

 

             ![](http://my.csdn.net/uploads/201208/05/1344142732_4454.png)              ![](http://my.csdn.net/uploads/201208/05/1344142753_3555.png)

 

接下来看如何使用，首先是把ZXing项目中的一些文件拷贝到我们自己的项目中，然后在Mainifest文件中进行配置权限：

 

 

 

**\[html]** [view plain](http://blog.csdn.net/tangren03/article/details/7831826?reload "view plain")[copy](http://blog.csdn.net/tangren03/article/details/7831826?reload "copy")

1. &lt;uses-permission android:name="android.permission.VIBRATE" /&gt;
2. &lt;uses-permission android:name="android.permission.CAMERA" /&gt;
3. &lt;uses-feature android:name="android.hardware.camera" /&gt;
4. &lt;uses-feature android:name="android.hardware.camera.autofocus" /&gt;

还有就是扫描界面Activity的配置：

 

 

**\[html]** [view plain](http://blog.csdn.net/tangren03/article/details/7831826?reload "view plain")[copy](http://blog.csdn.net/tangren03/article/details/7831826?reload "copy")

1. &lt;activity
2. android:configChanges="orientation|keyboardHidden"
3. android:name="com.zxing.activity.CaptureActivity"
4. android:screenOrientation="portrait"
5. android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
6. android:windowSoftInputMode="stateAlwaysHidden" &gt;
7. &lt;/activity&gt;

接下来是我自己项目的布局文件：

 

 

**\[html]** [view plain](http://blog.csdn.net/tangren03/article/details/7831826?reload "view plain")[copy](http://blog.csdn.net/tangren03/article/details/7831826?reload "copy")

01. &lt;?xml version="1.0" encoding="utf-8"?&gt;
02. &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03. android:layout\_width="fill\_parent"
04. android:layout\_height="fill\_parent"
05. android:background="@android:color/white"
06. android:orientation="vertical" &gt;
07. &lt;Button
08. android:id="@+id/btn\_scan\_barcode"
09. android:layout\_width="fill\_parent"
10. android:layout\_height="wrap\_content"
11. android:layout\_marginTop="30dp"
12. android:text="Open camera" /&gt;
13. &lt;LinearLayout
14. android:orientation="horizontal"
15. android:layout\_marginTop="10dp"
16. android:layout\_width="fill\_parent"
17. android:layout\_height="wrap\_content"&gt;
18. &lt;TextView
19. android:layout\_width="wrap\_content"
20. android:layout\_height="wrap\_content"
21. android:textColor="@android:color/black"
22. android:textSize="18sp"
23. android:text="Scan result：" /&gt;
24. &lt;TextView
25. android:id="@+id/tv\_scan\_result"
26. android:layout\_width="fill\_parent"
27. android:textSize="18sp"
28. android:textColor="@android:color/black"
29. android:layout\_height="wrap\_content" /&gt;
30. &lt;/LinearLayout&gt;
31. &lt;EditText
32. android:id="@+id/et\_qr\_string"
33. android:layout\_width="fill\_parent"
34. android:layout\_height="wrap\_content"
35. android:layout\_marginTop="30dp"
36. android:hint="Input the text"/&gt;
37. &lt;Button
38. android:id="@+id/btn\_add\_qrcode"
39. android:layout\_width="fill\_parent"
40. android:layout\_height="wrap\_content"
41. android:text="Generate QRcode" /&gt;
42. &lt;ImageView
43. android:id="@+id/iv\_qr\_image"
44. android:layout\_width="wrap\_content"
45. android:layout\_height="wrap\_content"
46. android:layout\_marginTop="10dp"
47. android:layout\_gravity="center"/&gt;
48. &lt;/LinearLayout&gt;

 

下面是主Activity的代码，主要功能是打开扫描框、显示扫描结果、根据输入的字符串生成二维码图片：

 

 

**\[java]** [view plain](http://blog.csdn.net/tangren03/article/details/7831826?reload "view plain")[copy](http://blog.csdn.net/tangren03/article/details/7831826?reload "copy")

01. public class BarCodeTestActivity extends Activity {
02. /\** Called when the activity is first created. \*/
03. private TextView resultTextView;
04. private EditText qrStrEditText;
05. private ImageView qrImgImageView;
06. @Override
07. public void onCreate(Bundle savedInstanceState) {
08. super.onCreate(savedInstanceState);
09. setContentView(R.layout.main);
10. resultTextView = (TextView) this.findViewById(R.id.tv\_scan\_result);
11. qrStrEditText = (EditText) this.findViewById(R.id.et\_qr\_string);
12. qrImgImageView = (ImageView) this.findViewById(R.id.iv\_qr\_image);
13. Button scanBarCodeButton = (Button) this.findViewById(R.id.btn\_scan\_barcode);
14. scanBarCodeButton.setOnClickListener(new OnClickListener() {
15. @Override
16. public void onClick(View v) {
17. //打开扫描界面扫描条形码或二维码
18. Intent openCameraIntent = new Intent(BarCodeTestActivity.this,CaptureActivity.class);
19. startActivityForResult(openCameraIntent, 0);
20. }
21. });
22. Button generateQRCodeButton = (Button) this.findViewById(R.id.btn\_add\_qrcode);
23. generateQRCodeButton.setOnClickListener(new OnClickListener() {
24. @Override
25. public void onClick(View v) {
26. try {
27. String contentString = qrStrEditText.getText().toString();
28. if (!contentString.equals("")) {
29. //根据字符串生成二维码图片并显示在界面上，第二个参数为图片的大小（350\*350）
30. Bitmap qrCodeBitmap = EncodingHandler.createQRCode(contentString, 350);
31. qrImgImageView.setImageBitmap(qrCodeBitmap);
32. }else {
33. Toast.makeText(BarCodeTestActivity.this, "Text can not be empty", Toast.LENGTH\_SHORT).show();
34. }
35. } catch (WriterException e) {
36. // TODO Auto-generated catch block
37. e.printStackTrace();
38. }
39. }
40. });
41. }
42. @Override
43. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
44. super.onActivityResult(requestCode, resultCode, data);
45. //处理扫描结果（在界面上显示）
46. if (resultCode == RESULT\_OK) {
47. Bundle bundle = data.getExtras();
48. String scanResult = bundle.getString("result");
49. resultTextView.setText(scanResult);
50. }
51. }
52. }

其中生成二维码图片的代码在EncodingHandler.java中：

 

 

**\[java]** [view plain](http://blog.csdn.net/tangren03/article/details/7831826?reload "view plain")[copy](http://blog.csdn.net/tangren03/article/details/7831826?reload "copy")

01. public final class EncodingHandler {
02. private static final int BLACK = 0xff000000;
03. public static Bitmap createQRCode(String str,int widthAndHeight) throws WriterException {
04. Hashtable&lt;EncodeHintType, String&gt; hints = new Hashtable&lt;EncodeHintType, String&gt;();
05. hints.put(EncodeHintType.CHARACTER\_SET, "utf-8");
06. BitMatrix matrix = new MultiFormatWriter().encode(str,
07. BarcodeFormat.QR\_CODE, widthAndHeight, widthAndHeight);
08. int width = matrix.getWidth();
09. int height = matrix.getHeight();
10. int\[] pixels = new int\[width * height];
11. for (int y = 0; y &lt; height; y++) {
12. for (int x = 0; x &lt; width; x++) {
13. if (matrix.get(x, y)) {
14. pixels\[y * width + x] = BLACK;
15. }
16. }
17. }
18. Bitmap bitmap = Bitmap.createBitmap(width, height,
19. Bitmap.Config.ARGB\_8888);
20. bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
21. return bitmap;
22. }
23. }

最后是在哪里对扫描结果进行解码，进入CaptureActivity.java找到下面这个方法便可以对自己对结果进行操作：

 

 

**\[java]** [view plain](http://blog.csdn.net/tangren03/article/details/7831826?reload "view plain")[copy](http://blog.csdn.net/tangren03/article/details/7831826?reload "copy")

01. /\**
02. * Handler scan result
03. * @param result
04. * @param barcode
05. \*/
06. public void handleDecode(Result result, Bitmap barcode) {
07. inactivityTimer.onActivity();
08. playBeepSoundAndVibrate();
09. String resultString = result.getText();
10. //FIXME
11. if (resultString.equals("")) {
12. Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH\_SHORT).show();
13. }else {
14. //          System.out.println("Result:"+resultString);
15. Intent resultIntent = new Intent();
16. Bundle bundle = new Bundle();
17. bundle.putString("result", resultString);
18. resultIntent.putExtras(bundle);
19. this.setResult(RESULT\_OK, resultIntent);
20. }
21. CaptureActivity.this.finish();
22. }

以上过程没有把每一步的详细步骤写出来，整体思路基本大致如上，源码下载：[源码](http://download.csdn.net/detail/tangren03/4477631)