編輯:Android 開發實例
先前我寫過一篇用 Google ZXing 做即時掃描的文章,成品刻意模仿微信那套交互體驗,有興趣的讀者可以對照著看。不過實務上經常碰到另一種情境:要讀的二維碼並不在眼前,而是早已躺在手機相簿中的一張圖片。這時候要做的就不是即時取像,而是把既有檔案解開來。
整體流程其實只有三段:先讓使用者從相簿挑一張圖,接著取得該圖的真實路徑,最後交給 ZXing 解碼。我這次是直接在原本的掃描工程上擴充,沒有另開新專案,並在掃描頁面的標題列右側補上一個 ImageButton 作為相簿入口,圖示沿用微信素材。
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:background="@drawable/mmtitle_bg_alpha" >
- <Button
- android:id="@+id/button_back"
- android:layout_width="75.0dip"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:background="@drawable/mm_title_back_btn"
- android:text="返回"
- android:textColor="@android:color/white" />
- <TextView
- android:id="@+id/textview_title"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerHorizontal="true"
- android:layout_centerVertical="true"
- android:gravity="center_vertical"
- android:text="二維碼掃描"
- android:textColor="@android:color/white"
- android:textSize="18sp" />
- <ImageButton
- android:id="@+id/button_function"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentRight="true"
- android:layout_marginRight="2dip"
- android:background="@drawable/mm_title_right_btn"
- android:minWidth="70dip"
- android:src="@drawable/mm_title_btn_menu_normal" />
- </RelativeLayout>
在 MipcaActivityCapture 中掛上點擊監聽,按下按鈕後以系統的內容選擇器開啟相簿。這裡用 Intent.ACTION_GET_CONTENT 搭配 image/* 的型別,讓系統把所有可能的來源(相簿、檔案總管、雲端硬碟等)都列出來:
- //打開手機中的相冊
- Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); //"android.intent.action.GET_CONTENT"
- innerIntent.setType("image/*");
- Intent wrapperIntent = Intent.createChooser(innerIntent, "選擇二維碼圖片");
- this.startActivityForResult(wrapperIntent, REQUEST_CODE);
因為用的是 startActivityForResult,使用者選好圖片後會回到 onActivityResult 這個回呼點。 here 我們先用 ContentResolver 把 Uri 換算成實際檔案路徑,再開一條子執行緒去解碼——圖片解碼與二維碼運算都頗耗時,放在主執行緒很容易觸發 ANR,所以一定要搬出去,結果再用 Handler 回丟給 UI:
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- if(resultCode == RESULT_OK){
- switch(requestCode){
- case REQUEST_CODE:
- //獲取選中圖片的路徑
- 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();
- mProgress = new ProgressDialog(MipcaActivityCapture.this);
- mProgress.setMessage("正在掃描...");
- mProgress.setCancelable(false);
- mProgress.show();
- new Thread(new Runnable() {
- @Override
- public void run() {
- Result result = scanningImage(photo_path);
- if (result != null) {
- Message m = mHandler.obtainMessage();
- m.what = PARSE_BARCODE_SUC;
- m.obj = result.getText();
- mHandler.sendMessage(m);
- } else {
- Message m = mHandler.obtainMessage();
- m.what = PARSE_BARCODE_FAIL;
- m.obj = "Scan failed!";
- mHandler.sendMessage(m);
- }
- }
- }).start();
- break;
- }
- }
- }
ZXing 的 QRCodeReader 提供了 decode(BinaryBitmap image, Map<DecodeHintType, ?> hints),只要把圖片包成 BinaryBitmap 就能拿到結果。這裡有兩個值得留意的細節:
第一是編碼問題。二維碼內容如果是中文,預設解出來常常是亂碼,所以我們透過 hint 明確指定 UTF-8。第二是記憶體問題。手機相片的解析度動輒數千像素,直接 decode 進記憶體很容易 OOM;實務上的做法是先用 inJustDecodeBounds = true 只讀取尺寸資訊,據此算出 inSampleSize 做降採樣,把圖片壓縮到 200 像素上下再真正解碼。二維碼的定位標記在這個尺寸下仍然清晰可辨,運算量卻大幅下降。
- /**
- * 掃描二維碼圖片的方法
- * @param path
- * @return
- */
- public Result scanningImage(String path) {
- if(TextUtils.isEmpty(path)){
- return null;
- }
- Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
- 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 則是格式不支援。成功時回傳的 Result 物件封裝了整組解碼結果,一行 getText() 就能把內容取出來。
不少朋友抓下 demo 後會遇到 Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/google/zxing/BarcodeFormat;。這個錯誤跟程式邏輯無關,單純是專案裡放了兩份功能重複的 JAR,把多餘的那個刪掉即可。
原文轉自:https://blog.csdn.net/xiaanming/article/details/14450809
Android 如何解析 JSON:從 API 回傳資料中取出欄位值
JSON 的全名是 JavaScript Object Notation,是一種與程式語言無關的資料交換格式。相較於 XML,它沒有冗長的標籤,結構清楚、體積更小,解析速
Android 本地化實戰:讓 App 說出使用者的語言
同一支 App,可能會在幾十個國家的裝置上執行。要讓它在不同市場都顯得自然,就不能把文字硬寫在程式碼裡,而必須處理語言環境(Locale)造成的差異——不只是文字,還包含
用 MediaPlayer 實作 Android 音樂播放器(含進度條與 ±5 秒跳轉)
要在 App 裡播放一段音樂,Android 給了你不少選擇,但最常被拿出來用的仍是 MediaPlayer。它把底層的播放服務包成一個好操作的物件,不論音樂是打包在 A
Android MediaPlayer 教學:播放、暫停與快轉的完整實作
Android 提供多種播放音訊與影片的方式,其中最通用的就是 MediaPlayer 類別。它被封裝在系統的媒體播放服務之上,讓你能用幾行程式碼就完成播放控制。 取得播