最近 公司的项目上有 扫描二维码功能,当然必不可少的就会有读取本地二维码需求。首先就是跳转到本地相册,如下代码:
/**
* show images in the android device media store
*/
public static void showPictures(Activity a,int type){
Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT);
String IMAGE_UNSPECIFIED = "image/*";
innerIntent.setType(IMAGE_UNSPECIFIED);
a.startActivityForResult(innerIntent, type);
}
在 onActivityResult中获取图片路径,
Uri uri = data.getData();
String strPath = uri.getPath();
发现得到的path路径值不是图片在我们手机上的历经,在根据这个路径值获取图片或得到null,不知为啥,
这在大多数手机一般都没问题,但是我用的是红米手机,巨坑的手机之一,之前一直觉得搞开发魅族手机很坑了,原来小米也算其一啊。
然后再onActivityResult做如下处理,结果是二维码,和非二维码图片都可以扫描,并做出相应的处理;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Logger.i("test", "---------------------3---------------");
if (data != null) {
mProgress = new ProgressDialog(CaptureActivity.this);
mProgress.setMessage("已扫描,正在处理...");
mProgress.setCancelable(false);
mProgress.show();
final ContentResolver resolver = getContentResolver();
Uri uri = data.getData();
if (requestCode == TypeCodeing.REQUESTCODE_CAPTURE
&& resultCode == RESULT_OK) {
if (!TextUtils.isEmpty(uri.getAuthority())) {
Logger.e(this, "url=" + data.getData() + "=resolver=" + resolver);
Cursor cursor = resolver.query(uri, new String[]{MediaStore.Images.Media.DATA}, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
photoPath = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
}
} else {
ToastUtil.show("啥也没扫出来,");
mProgress.dismiss();
return;
}
}else{
photoPath = uri.getPath();
}
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
Looper.prepare();
String result = parsLocalPic(photoPath);
Logger.e(this, "result=" + result + "=photoPath="
+ photoPath);
if (result != null) {
if (handler == null) {
handler = new CaptureActivityHandler(
CaptureActivity.this);
}
Message msg = new Message();
msg.obj = result;
msg.what = R.id.decode_succeeded;
handler.sendMessageDelayed(msg, 1000);
} else {
if (mProgress != null && mProgress.isShowing()) {
mProgress.dismiss();
}
ToastUtil.show("啥也没扫出来,要不换张图片试试( •̥́ ˍ •̀ू )");
}
Looper.loop();
}
}).start();
}
} else {
Logger.e(this, "data==" + data);
ToastUtil.show("empty");
return;
}
}
ok 搞定