一般调用系统相机的代码:
filePath = ImageUtil.getCacheFilePath(this, StaticValue.PHOTO_PROTOCOL_ENTRUST);
File file = new File(filePath);
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intentFromCapture.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intentFromCapture, CAMERA_ENTURST_PHOTO_REQ_CODE);
在OnActivityResult回调的时候发现intetn的data值为null。如果企图通过data取值就会崩溃,
查看相关资料,Android调用相机相关源码:
得出在手动指定了uri之后,data就会为空。
// First handle the no crop case -- just return the value. If the
// caller specifies a "save uri" then write the data to it's
// stream. Otherwise, pass back a scaled down version of the bitmap
// directly in the extras.
if (mSaveUri != null) { //如果指定了uri
OutputStream outputStream = null;
try {
outputStream = mContentResolver.openOutputStream(mSaveUri);
outputStream.write(data);
outputStream.close();
setResult(RESULT_OK); //只返回结果,不返回data数据
finish();
} catch (IOException ex) {
// ignore exception
} finally {
Util.closeSilently(outputStream);
}
} else { //默认情况不指定uri,会把data塞进result回调
Bitmap bitmap = createCaptureBitmap(data);
setResult(RESULT_OK, new Intent("inline-data").putExtra("data", bitmap));
finish();
}
解决办法:
①不指定uri,即,
Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentFromCapture, CAMERA_ENTURST_PHOTO_REQ_CODE);
使用系统默认的uri路径。此时data不为空。
可以在data里面取得相应的数据,
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case CAMERA_ENTURST_PHOTO_REQ_CODE:
if (resultCode == RESULT_OK) {
if (data != null) {
if(data.hasExtra("data")){
Bitmap bitmap = data.getParcelableExtra("data");
}
}
}
break;
}
}
②如文章开头指定uri,将图片路径定义全局,不使用data获取先关数据。(推荐)