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

Android ZXing 二維碼掃描實作:常見問題與解決方案

編輯:關於 Android 開發

Android ZXing 二維碼掃描實作:常見問題與解決方案

近期開發一款具備二維碼掃描功能的應用(基於開源專案 ZXing),以下記錄實作過程中遇到的問題及解決方式,希望對大家有所幫助。

一、添加相機權限

掃描需要調用相機,因此權限是首要且必須的設定,否則後續功能都無法進行:

<uses-permission android:name="android.permission.CAMERA" />

二、設置掃描框的大小

在 com.zxing.camera 包中,可透過修改以下常數值來調整掃描框大小:

private static final int MIN_FRAME_WIDTH = 240;
private static final int MIN_FRAME_HEIGHT = 240;
private static final int MAX_FRAME_WIDTH = 580;
private static final int MAX_FRAME_HEIGHT = 580;

三、實現二維碼的重複掃描

步驟一:在 com.zxing.decoding 包中找到 restartPreviewAndDecode() 方法,將其訪問修飾符由 private 改為 public。

步驟二:在掃描二維碼的 Activity 中添加重複掃描方法:

private void continuePreview() {
    SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
    SurfaceHolder surfaceHolder = surfaceView.getHolder();
    initCamera(surfaceHolder);
    if (handler != null) {
        handler.restartPreviewAndDecode();
    }
}

注意:直接呼叫此方法有時會出現 bug——多次掃描後返回上一個介面、再次進入時會出現黑屏。

解決方法:不直接呼叫 continuePreview(),而是在需要二次掃描時直接寫:

if (handler != null) {
    handler.restartPreviewAndDecode();
}

如此一來,即可避免重複掃描後再次進入時的黑屏問題。

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