我遇到了奇怪的行为。我想用Intent调出画廊。然后onActivityResult()我想采取Uri并将其转换为Bitmap。我面临的问题是首先选择图像会导致手机冻结几秒钟。然后,当它返回到onActivityResult()时,即使我选择了一个图像,resultCode值也是-1。我在步骤中遗漏了什么吗?
启动Gallery Intent
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, GALLERY_REQUEST_CODE);
我的onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST_CODE) {
Uri selectedImageUri = data.getData();
if (selectedImageUri != null) {
try {
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(
selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap mBitmap = BitmapFactory.decodeFile(filePath);
LogUtil.e(TAG, "mBitmap: " + mBitmap);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
mBitmap.compress(Bitmap.CompressFormat.PNG, 50, bs);
Intent intent = new Intent(CameraActivity.this,
SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("image", bs.toByteArray());
startActivity(intent);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
return;
}
}
更新: 我有清单的许可。我也收到了正确的Uri。但在选择图像后,我总是收到resultCode = -1。我似乎收到了一个失败的活页夹交易。
我可能错过任何权限吗?提前谢谢!
答案 0 :(得分:1)
要使此代码工作,您需要写入权限,检查清单中是否包含此代码。
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>