Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 二維碼生成與識別:基於 ZXing 庫的實戰(附源碼)

編輯:關於 Android 程式設計

二維碼可謂是移動互聯網時代最普及的技術之一,大街小巷、各類應用裡隨處可見。本文以實現為導向,帶大家用 Google 的 ZXing 庫完成兩件事:生成二維碼,以及通過攝像頭掃描識別二維碼。理論部分不做過多展開,有興趣的朋友可以自行研究源碼。

一、ZXing 庫簡介

ZXing 是一個開放源碼、用 Java 實現的多格式 1D/2D 條碼處理庫,它能調用手機攝像頭完成條形碼的掃描與解碼,支持 UPC-A、UPC-E、EAN-8、EAN-13、Code 39、Code 93 等多種格式,是二維碼/條形碼識別領域非常經典的開源方案。

二、ZXing 的主要類

了解幾個關鍵類有助於讀懂它的運作:

CaptureActivity:掃描器的啟動 Activity;

CaptureActivityHandler:解碼處理類,負責調用其他線程進行解碼;

DecodeThread:實際執行解碼的線程;

com.google.zxing.client.android.camera 包:攝像頭控制相關;

ViewfinderView:自定義 View,就是掃描時中間那個取景框。

三、生成二維碼

核心方法是 QRCodeWriter().encode,把字符串編碼成 BitMatrix,再逐像素還原成 Bitmap:

public void createQRImage(String url) {
    try {
        if (url == null || "".equals(url) || url.length() < 1) return;
        Hashtable<EncodeHintType, String> hints = new Hashtable<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        BitMatrix bitMatrix = new QRCodeWriter().encode(
            url, BarcodeFormat.QR_CODE, QR_WIDTH, QR_HEIGHT, hints);
        int[] pixels = new int[QR_WIDTH * QR_HEIGHT];
        for (int y = 0; y < QR_HEIGHT; y++) {
            for (int x = 0; x < QR_WIDTH; x++) {
                pixels[y * QR_WIDTH + x] = bitMatrix.get(x, y) ? 0xff000000 : 0xffffffff;
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(QR_WIDTH, QR_HEIGHT, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, QR_WIDTH, 0, 0, QR_WIDTH, QR_HEIGHT);
        sweepIV.setImageBitmap(bitmap);
    } catch (WriterException e) {
        e.printStackTrace();
    }
}

只要傳入一個合法的字符串(例如一個網址或 App 下載地址),就能生成對應的二維碼。這也是目前很多 App 推廣的主流方式——掃一下即可下載。

四、掃描識別二維碼

識別部分的關鍵在於相機的自動對焦回調。由於解碼較為耗時,ZXing 全程使用 Handler 作為線程通信機制,把解碼放在獨立線程裡進行,避免阻塞主線程導致 ANR。自動對焦完成後會重新請求預覽與解碼:

private void restartPreviewAndDecode() {
    if (state == State.SUCCESS) {
        state = State.PREVIEW;
        CameraManager.get().requestPreviewFrame(decodeThread.getHandler(), R.id.decode);
        CameraManager.get().requestAutoFocus(this, R.id.auto_focus);
        activity.drawViewfinder();
    }
}

解碼成功後,結果會被序列化保存,並通過消息通知界面進行處理:

public void handleDecode(final Result obj, Bitmap barcode) {
    playBeepSoundAndVibrate();
    AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    dialog.setTitle("掃描結果");
    dialog.setMessage(obj.getText());
    dialog.setNegativeButton("確定", (d, w) -> {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(obj.getText()));
        startActivity(intent);
        finish();
    });
    dialog.setPositiveButton("取消", (d, w) -> finish());
    dialog.create().show();
}

五、必備權限

由於涉及相機與自動對焦,記得在清單文件中申明相應權限:

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

六、小結

以上就是生成與識別二維碼的關鍵流程。ZXing 內部還有大量圖像處理知識值得深入學習,除了二維碼,它對各類條形碼也都有支持。二維碼作為移動開發的常用技術,值得大家花時間了解一番,說不定哪天就用上了。

ZXing 開源項目地址:https://code.google.com/p/zxing/

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