Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

用 ZXing 實現 Android 二維碼掃描與生成(從零開始學 Android)

編輯:Android 技術基礎

項目裡需要二維碼能力時,不必自己從零造輪子。Google 開源的 ZXing 是事實上的標準方案,條形碼與二維碼的掃描、生成都覆蓋到了。原理上兩者有點差別:掃描條形碼基本就是直接讀出編碼內容,而二維碼則可以自定義編碼格式,按需編解碼。

源碼可從 https://code.google.com/p/zxing/ 獲取,按官方文檔接入即可。本文使用的是精簡過的版本,刪去了一般場景用不到的文件,工程結構大致如下:

其中 encoding 包是自行補上的,功能是傳入一段字符串、生成對應的二維碼圖片並返回 Bitmap;其餘各包均來自 ZXing 原項目。掃描界面也做了改動:官方默認是橫向的,這裡改為縱向,並在頂部加了 Tab 與取消按鈕(camera.xml)。此外還需要 colors.xml、ids.xml 等資源文件,以及 libs 下的 jar 包。

先看效果

左圖是根據輸入字符串生成的二維碼,右圖是掃描後在界面上顯示結果:

              

點擊 Open Camera 打開掃描框(左圖),掃描條形碼的結果如下(右圖):

              

接入步驟

1. 拷貝文件並配置權限

把 ZXing 項目中的相關文件複製到自己的工程,然後在 Manifest 中聲明相機與震動權限:

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

2. 配置掃描 Activity

掃描界面需要全屏橫屏鎖定(此處改為 portrait)、隱藏軟鍵盤:

<activity
    android:configChanges="orientation|keyboardHidden"
    android:name="com.zxing.activity.CaptureActivity"
    android:screenOrientation="portrait"
    android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
    android:windowSoftInputMode="stateAlwaysHidden">
</activity>

3. 主界面布局

上半部分放掃描入口與結果展示,下半部分放二維碼生成的輸入框與預覽:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/white"
    android:orientation="vertical">

    <Button
        android:id="@+id/btn_scan_barcode"
        android:layout_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">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/black"
            android:textSize="18sp"
            android:text="Scan result:" />

        <TextView
            android:id="@+id/tv_scan_result"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:textColor="@android:color/black" />
    </LinearLayout>

    <EditText
        android:id="@+id/et_qr_string"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_gravity="center" />

</LinearLayout>

主 Activity 的三件事

打開掃描框、展示掃描結果、根據輸入生成二維碼,都在同一個 Activity 中完成:

public class BarCodeTestActivity extends Activity {

    private TextView resultTextView;
    private EditText qrStrEditText;
    private ImageView qrImgImageView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        resultTextView = (TextView) findViewById(R.id.tv_scan_result);
        qrStrEditText = (EditText) findViewById(R.id.et_qr_string);
        qrImgImageView = (ImageView) findViewById(R.id.iv_qr_image);

        // 打開掃描界面
        Button scanBarCodeButton = (Button) findViewById(R.id.btn_scan_barcode);
        scanBarCodeButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent openCameraIntent = new Intent(BarCodeTestActivity.this, CaptureActivity.class);
                startActivityForResult(openCameraIntent, 0);
            }
        });

        // 根據字符串生成二維碼
        Button generateQRCodeButton = (Button) findViewById(R.id.btn_add_qrcode);
        generateQRCodeButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    String contentString = qrStrEditText.getText().toString();
                    if (!contentString.equals("")) {
                        // 第二個參數為圖片尺寸 350*350
                        Bitmap qrCodeBitmap = EncodingHandler.createQRCode(contentString, 350);
                        qrImgImageView.setImageBitmap(qrCodeBitmap);
                    } else {
                        Toast.makeText(BarCodeTestActivity.this,
                                "Text can not be empty", Toast.LENGTH_SHORT).show();
                    }
                } catch (WriterException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 處理掃描結果
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            resultTextView.setText(scanResult);
        }
    }
}

二維碼生成的實現

EncodingHandler 是我們在 ZXing 基礎上補上的一層,做法是用 MultiFormatWriter 編碼出 BitMatrix,再逐像素轉成 Bitmap:

public final class EncodingHandler {

    private static final int BLACK = 0xff000000;

    public static Bitmap createQRCode(String str, int widthAndHeight) throws WriterException {
        Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");

        BitMatrix matrix = new MultiFormatWriter().encode(str,
                BarcodeFormat.QR_CODE, widthAndHeight, widthAndHeight);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];

        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = BLACK;
                }
            }
        }

        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }
}

指定 CHARACTER_SET 為 utf-8 是必要的一步,否則包含中文的內容會出現亂碼。

在哪裡接管掃描結果

掃描完成後,ZXing 會呼叫 CaptureActivity 中的 handleDecode。自定義業務邏輯就寫在這裡:

/**
 * Handler scan result
 */
public void handleDecode(Result result, Bitmap barcode) {
    inactivityTimer.onActivity();
    playBeepSoundAndVibrate();

    String resultString = result.getText();
    if (resultString.equals("")) {
        Toast.makeText(CaptureActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
    } else {
        Intent resultIntent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("result", resultString);
        resultIntent.putExtras(bundle);
        setResult(RESULT_OK, resultIntent);
    }
    finish();
}

在真實項目中,這裡通常不會只是把字符串顯示出來,而是據內容做分發:是鏈接就跳轉瀏覽器,是名片信息就寫入聯繫人,是自家協議格式就交給業務層解析。

小結

ZXing 的接入成本並不高,工作量集中在三處:拷貝並裁剪源碼、調整掃描界面適配自己的設計、在 handleDecode 中接入業務。生成能力則靠一個幾十行的 EncodingHandler 補齊,掃描與生成兩端就都能自給自足了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved