问题描述
- URI 和 ACTION_GET_CONTENT
-
我想从一个 android 设备中选择一个图像,当我使用下面这段代码时,什么时候要使用 ACTION_GET_CONTENT intent 呢?// 随机获取图像 public static Uri getRandomImage(ContentResolver resolver) { String[] projection = new String[] { BaseColumns._ID }; Uri uri = new Random().nextInt(1) == 0 ? Media.EXTERNAL_CONTENT_URI : Media.INTERNAL_CONTENT_URI; Cursor cursor = Media.query(resolver, uri, projection, null, MediaColumns._ID); if (cursor == null || cursor.getCount() <= 0) { return null; } cursor.moveToPosition(new Random().nextInt(cursor.getCount())); return Uri.withAppendedPath(uri, cursor.getString(0)); }
解决方案
如果你想从android gallery 中选择图像,可以这样
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 100);
要返回结果
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(
selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
}
}
}
解决方案二:
protected void select() {
Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 1);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
switch (requestCode) {
case 1:
Uri uri = data.getData();
String[] col = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(uri, col, null, null, null);
c.moveToFirst();
String imgpath = c.getString(c.getColumnIndex(col[0]));
iv_imgage.setImageURI(Uri.parse(imgpath));
c.close();
break;
default:
break;
}
}
}
时间: 2024-10-03 00:18:38