Android: Let user pick image or video from Gallery

2019-02-01 05:28发布

Is it possible to to start Gallery in such a way so both pictures and videos are shown?

Thanks

8条回答
兄弟一词,经得起流年.
2楼-- · 2019-02-01 06:25

You start the gallery as such:

Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/* video/*");
startActivityForResult(pickIntent, IMAGE_PICKER_SELECT);

then in your onActivityResult you can check if video or image was selected by doing this:

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == RESULT_OK) {
    Uri selectedMediaUri = data.getData();
    if (selectedMediaUri.toString().contains("image")) {
        //handle image
    } else  if (selectedMediaUri.toString().contains("video")) {
        //handle video
    }
}
查看更多
兄弟一词,经得起流年.
3楼-- · 2019-02-01 06:28

When you need to determine what kind of content was returned, you can do it using content resolver to get the MIME type of the returned content:

if( data != null) {
    Uri selectedUri = data.getData();   
    String[] columns = { MediaStore.Images.Media.DATA,
                         MediaStore.Images.Media.MIME_TYPE };

    Cursor cursor = getContentResolver().query(selectedUri, columns, null, null, null);
    cursor.moveToFirst();

    int pathColumnIndex     = cursor.getColumnIndex( columns[0] );
    int mimeTypeColumnIndex = cursor.getColumnIndex( columns[1] );

    String contentPath = cursor.getString(pathColumnIndex);
    String mimeType    = cursor.getString(mimeTypeColumnIndex);
    cursor.close();

    if(mimeType.startsWith("image")) {
          //It's an image
    }
    else if(mimeType.startsWith("video")) {
         //It's a video
    }       
}
else {
    // show error or do nothing
}
查看更多
登录 后发表回答