新浪博客

Android获取本地图片之ACTION_GET_CONTENT与ACTION_PICK区别

2023-06-20 11:51阅读:
我们都知道下面两种方法都可以打开Android本地图库:
Intent.ACTION_GET_CONTENT
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType('image
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPathFromUriOnKitKat(Activity act, Uri uri) {

String path = null;
if (DocumentsContract.isDocumentUri(act, uri)) {
// 如果是document类型的Uri,则通过document id处理
String docId = DocumentsContract.getDocumentId(uri);
if ('com.android.providers.media.documents'.equals(uri.getAuthority())) {
String id = docId.split(':')[1]; // 解析出数字格式的id
String selection = MediaStore.Images.Media._ID + '=' + id;
path = getPathFromUri(act, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
} else if ('com.android.providers.downloads.documents'.equals(uri.getAuthority())) {
Uri contentUri = ContentUris.withAppendedId(Uri.parse('content://downloads/public_downloads'), Long.valueOf(docId));
path = getPathFromUri(act, contentUri, null);
}
} else if ('content'.equalsIgnoreCase(uri.getScheme())) {
// 如果是content类型的Uri,则使用普通方式处理
path = getPathFromUri(act, uri, null);
} else if ('file'.equalsIgnoreCase(uri.getScheme())) {
// 如果是file类型的Uri,直接获取图片路径即可
path = uri.getPath();
}
return path;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
Android4.4之前处理:
public static String getPathFromUriBeforeKitKat(Activity act, Uri uri) {
return getPathFromUri(act, uri, null);
}
private static String getPathFromUri(Activity act, Uri uri, String selection) {
String path = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = act.getContentResolver().query(uri, projection, selection,null,null);
if(cursor != null){
if(cursor.moveToFirst()){
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
}
cursor.close();
}
return path;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Intent.ACTION_GET_CONTENT不仅仅可以获取本地的图片,还可以获取本地的音频,视频等,同样Intent.ACTION_PICK不仅仅获取图片,还可以获取本地联系人等
(一)、调用本地联系人:
Intent intent=newIntent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
startActivityForResult(intent,PICK_CONTACT);
(二)、调用图库,获取所有本地图片:
Intent imageIntent=newIntent(Intent.ACTION_GET_CONTENT);
imageIntent.setType('image/*');
startActivityForResult(imageIntent,PICK_IMAGE);
(三)、调用音乐,获取所有本地音乐文件:
Intent audioIntent=newIntent(Intent.ACTION_GET_CONTENT);
audioIntent.setType('audio/*');
startActivityForResult(audioIntent,PICK_AUDIO);
(四)、调用图库,获取所有本地视频文件:
Intent videoIntent=newIntent(Intent.ACTION_GET_CONTENT);
videoIntent.setType('video/*');
startActivityForResult(videoIntent,PICK_VIDEO);
————————————————
版权声明:本文为CSDN博主「CoderCF」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/chengfu116/article/details/74923161

我的更多文章

下载客户端阅读体验更佳

APP专享