編輯:關於 Android 程式設計
先前做過一個仿微信風格的 ZXing 掃描頁(條碼即時預覽那種),但有時需求不太一樣:使用者手上已經有一張含二維碼的圖片,想直接從相簿挑出來解。本文就在原本的掃描工程上加這個功能。
標題列沿用微信的樣式資源,右側放一個 ImageButton 作為「從相簿選圖」的入口,左側保留返回鍵,中間是標題文字。佈局以 RelativeLayout 為底,靠 layout_alignParentRight 把按鈕推到右側即可。
點擊監聽中用 ACTION_GET_CONTENT 搭配 image/* 的型別開啟系統相簿,並包一層 Intent.createChooser 讓標題顯示為「選擇二維碼圖片」:
Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
innerIntent.setType("image/*");
Intent wrapperIntent = Intent.createChooser(innerIntent, "選擇二維碼圖片");
this.startActivityForResult(wrapperIntent, REQUEST_CODE);
用 startActivityForResult 而非 startActivity,是因為我們需要拿到使用者選的那張圖。回到 onActivityResult 後,先過濾 requestCode 與 resultCode,再用 ContentResolver 查詢 Uri 對應的實際路徑:
Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
if (cursor.moveToFirst()) {
photo_path = cursor.getString(
cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
拿到路徑後顯示一個不可取消的 ProgressDialog,並在子執行緒中進行解碼,避免解析耗時引發 ANR,結果再透過 Handler 回主執行緒更新 UI:
new Thread(new Runnable() {
@Override
public void run() {
Result result = scanningImage(photo_path);
Message m = mHandler.obtainMessage();
m.what = (result != null) ? PARSE_BARCODE_SUC : PARSE_BARCODE_FAIL;
m.obj = (result != null) ? result.getText() : "Scan failed!";
mHandler.sendMessage(m);
}
}).start();
ZXing 提供的 QRCodeReader 搭配 decode(BinaryBitmap, Map) 就能完成解析。實作上有兩個細節值得注意:一是設定字元集為 UTF8,否則中文內容容易亂碼;二是先用 inJustDecodeBounds 讀取原圖尺寸做縮放,避免大圖直接進記憶體造成 OOM。
public Result scanningImage(String path) {
if (TextUtils.isEmpty(path)) return null;
Hashtable<DecodeHintType, String> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "UTF8");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
scanBitmap = BitmapFactory.decodeFile(path, options);
options.inJustDecodeBounds = false;
int sampleSize = (int) (options.outHeight / (float) 200);
if (sampleSize <= 0) sampleSize = 1;
options.inSampleSize = sampleSize;
scanBitmap = BitmapFactory.decodeFile(path, options);
RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
try {
return reader.decode(bitmap1, hints);
} catch (NotFoundException e) {
e.printStackTrace();
} catch (ChecksumException e) {
e.printStackTrace();
} catch (FormatException e) {
e.printStackTrace();
}
return null;
}
三個例外各有含義:NotFoundException 代表圖中找不到符合的碼,ChecksumException 代表定位到了但資料校驗失敗(通常是影像模糊或反光),FormatException 則是資料結構不合法。UI 上可以據此給出不同提示,使用者體驗會好很多。
sampleSize 只看高度,長寬比極端的圖可能仍偏大,實務上取寬高的較小值來算會更穩。另外,解碼完記得回收 Bitmap;若專案已遷到 AndroidX,可考慮 CameraX 搭配 ML Kit 的 barcode scanning,能同時拿到即時預覽與相簿解碼兩種能力,也不必自行維護 ZXing 這份已停止更新的程式碼。
Android Fragment 入門:概念解析與兩種核心用法
前陣子在調整 ViewPager 時,我越發覺得「ViewPager + Fragment」的組合來得靈活好用,於是乾脆把 Fragment 這個知識點重新梳理了一遍,趁
Android 動態布局入門與 NinePatch 圖片解析
擺脫 XML 布局多數 Android 開發者在學習初期,都會透過 layout 目錄下的 XML 檔案來定義畫面。XML 布局結構清楚、可預覽,非常方便。但在某些情境下
Android 集成信鴿推送的完整流程與常見問題
在移動應用中,推送已經成為常見能力。常見的推送方案包括小米推送、極光推送、個推以及騰訊信鴿推送。本文以信鴿推送為例,梳理 Android 項目集成過程中的關鍵步驟與常見問
java/android 設計模式學習筆記(2):觀察者模式
觀察者模式是行為型設計模式中的經典方案,它定義了一對多的依賴關係:當主題對象的狀態發生變化時,所有依賴它的觀察者都會自動收到通知並更新。在 Android 開發中,這一模