標籤:int null extern 掃描二維碼 style selected tor 處理 bin
項目中添加裝置操作需要掃描二維碼,考慮到多種掃碼方式,也添加直接識別二維碼圖片的操作。
首先跳轉系統相簿選取圖片
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, DEVICE_PHOTO_REQUEST);
接著將選取的圖片展示到介面
1 @Override 2 public void onActivityResult(int requestCode, int resultCode, Intent data) { 3 //使用者沒有進行有效設定作業,返回 4 if (requestCode == Activity.RESULT_CANCELED ){ 5 ToastUtil.showToast(AddDeviceActivity.this, R.string.cancel); 6 return; 7 } 8 if (DEVICE_PHOTO_REQUEST == requestCode){ 9 if (null != data) {10 Uri selectedImage = data.getData();11 String[] filePathColumns = {MediaStore.Images.Media.DATA};12 String imagePath;13 Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null, null, null);14 if (c != null) {15 c.moveToFirst();16 int columnIndex = c.getColumnIndex(filePathColumns[0]);17 imagePath = c.getString(columnIndex);18 c.close();19 20 Bitmap bm = BitmapFactory.decodeFile(imgPath);21 img_code.setImageBitmap(bm);22 } else {23 ToastUtil.showToast(this, "圖片路徑為空白");24 }25 }26 }27 super.onActivityResult(requestCode, resultCode, data);28 }29
然後用第三包的方法解碼識別(需要匯入‘cn.bingoogolapple:bga-zxing:[email protected]‘),注意自己處理一下匿名 AsyncTask 內部類導致的Activity 泄漏問題
img_code.setDrawingCacheEnabled(true); final Bitmap bmp = img_code.getDrawingCache(); new AsyncTask<Void, Void, String>() { @Override protected String doInBackground(Void... params) { return QRCodeDecoder.syncDecodeQRCode(bmp); } @Override protected void onPostExecute(String result) { if (TextUtils.isEmpty(result)) { Toast.makeText(AddDeviceActivity.this, "二維碼解析失敗", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(AddDeviceActivity.this, result, Toast.LENGTH_SHORT).show(); } } }.execute();
android選取系統相簿圖片後,識別圖中二維碼