項目中添加設備操作需要掃描二維碼,考慮到多種掃碼方式,也添加直接識別二維碼圖片的操作。
首先跳轉系統相冊選取圖片
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:1.1.9@aar'),注意自己處理一下匿名 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();