如何从图库中选择视频并获取真实路径?

问题描述:

我可以使用此代码打开图库

I can open the gallery with this code,

    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("video/*");

    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST );

它在三星Galaxy S5上运行良好.但是在某些手机中,图像会与视频一起显示.

It works well on a Samsung Galaxy S5. But in some phones, images are displayed along with videos.

我需要对代码进行哪些更改才能打开图库以显示个视频?

What changes do I need to do to the code to open the gallery to display only videos?

返回结果后,如何获取所选视频的真实路径?

How can I get the real path of the selected video when the results are returned?


这是从图库中选择后获取视频路径的完整代码.


Here is the full code to get the video path after selecting from gallery.

Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Video"),REQUEST_TAKE_GALLERY_VIDEO);

public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_TAKE_GALLERY_VIDEO) {
                Uri selectedImageUri = data.getData();

                // OI FILE Manager
                filemanagerstring = selectedImageUri.getPath();

                // MEDIA GALLERY
                selectedImagePath = getPath(selectedImageUri);
                if (selectedImagePath != null) {

                    Intent intent = new Intent(HomeActivity.this,
                            VideoplayAvtivity.class);
                    intent.putExtra("path", selectedImagePath);
                    startActivity(intent);
                }
            }
        }
    }

    // UPDATED!
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Video.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            // HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
            // THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }