select-multiple-images-from-android,如何获得Uris?

时间:2014-01-12 03:48:32

标签: android

描述:http://www.rqgg.net/topic/vrvkz-select-multiple-images-from-android-gallery.html

如果调用者可以处理多个返回的项目(用户执行多项选择),那么它可以指定EXTRA_ALLOW_MULTIPLE来指示这一点。

这非常有趣。他们在这里指的是用户可以选择多个项目的用例吗?

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    public void selectPhotos(){
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        startActivityForResult(Intent.createChooser(intent,
                "select multiple images"), SELECT_PHOTOS_RESULT);
    }


protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        super.onActivityResult(requestCode, resultCode, intent);

        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                case SELECT_PHOTOS_RESULT:
                    //how to get the Uris?
                    ...
                    break;

        }

    }

1 个答案:

答案 0 :(得分:21)

可能我迟迟没有回答这个问题。可能会帮助正在寻找答案的人。

    if (intent != null) {
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        Uri uri = item.getUri();

                        //In case you need image's absolute path
                        String path= getRealPathFromURI(getActivity(), uri)
                    }
                }
            }

public String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null,
                null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

注意:getClipData()调用需要最低API级别16