如果需要从本机图片中选择一张,可以通过Intent.ACTION_GET_CONTENT调出界面,选择后再处理返回的Intent。
调用Intent.ACTION_GET_CONTENT调出选择页面
Intent intent = newIntent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
activity.startActivityForResult(intent, 1);
onActivityResult中
情况1——content数据
Intent {dat=content://media/external/images/media/39617 }
Uri uri =data.getData();
String[] proj ={MediaStore.Images.Media.DATA, MediaStore.Images.Media.ORIENTATION};
Cursor cursor =activity.getContentResolver().query(uri, proj, null, null, null);
if (cursor == null)return null;
if(cursor.moveToFirst()) {
intdata_index = cursor.getColumnIndexOrThrow(proj[0]);
intorientation_index = cursor.getColumnIndexOrThrow(proj[1]);
cursor.getString(data_index);
cursor.getInt(orientation_index);
}
cursor.close();
取出实际路径为 /storage/sdcard0/DCIM/Camera/IMG_20140805_150522.jpg
情况2——file数据
Intent { dat=file:///storage/sdcard0/MIUI/Gallery/cloud/.thumbnailFile/d495cc46dd7635b4d3c5dde081218c876326e741.jpgtyp=image/jpeg }
Uri uri =data.getData();
uri.getPath()
取出实际路径为 /storage/sdcard0/MIUI/Gallery/cloud/.thumbnailFile/d495cc46dd7635b4d3c5dde081218c876326e741.jpg
情况3——新版Uri数据
4.4引入,如content://com.android.providers.media.documents/document/image:139797,content://com.android.externalstorage.documents/document/image:139797,content://com.android.providers.downloads.documents/document/image:139797
Intent {dat=content://com.android.providers.media.documents/document/image:139797flg=0x1 }
Uri uri =data.getData();
对于最近和图像,URI格式为
content://com.android.providers.media.documents/document/image%3A140449
context.getContentResolver().query时的参数
Uri: content: //media/external/images/media
Selection: _id=?
SelectionArgs: 140449(即image的id)
对于下载内容,URI格式为content://com.android.providers.downloads.documents/document/692
context.getContentResolver().query时的参数
URI: content://downloads/public_downloads/692
对于外部存储,URI格式为content://com.android.externalstorage.documents/document/primary:Mini.jpg
context.getContentResolver().query时的参数
Environment.getExternalStorageDirectory()+ "/" + split[1]极为文件路径
/storage/emulated/0/Mini.jpg
如果编译所用api版本低于4.4,可以采用反射方式尝试调用本地包中接口,如
public static String getDocumentId(Uri uri){
String res = null;
try {
Class<?> c =Class.forName("android.provider.DocumentsContract");
Method get =c.getMethod("getDocumentId", Uri.class);
res = (String)get.invoke(c, uri);
} catch (Exception ignored) {
ignored.getMessage();
}
return res;
}