Daniele
Daniele

Reputation: 4343

Android - Limit Intent.ACTION_GET_CONTENT to a specific file extension

In my app I need to get an Audio file from the user's library.

to do it I'm calling this Intent:

Intent selectIntent = new Intent(Intent.ACTION_GET_CONTENT);
            selectIntent.setType("audio/*");
            startActivityForResult(selectIntent, SONG_REQUEST_CODE); 

by having "audio/*" as an argument for the setType() method, I'm getting every audio file, indipendently from it's extension.

All I need to do is to filter it to only have, let's say, .mp3 files selectable

I tried to do it by having ".mp3", "audio/.mp3" as an argument for the setType() method, but none of them worked.

Upvotes: 2

Views: 2147

Answers (2)

UltimateDevil
UltimateDevil

Reputation: 2847

I am using following code

Intent mp3Intent;
mp3Intent= new Intent();
mp3Intent.setAction(Intent.ACTION_GET_CONTENT);
mp3Intent.setType("audio/mpeg");
startActivityForResult(Intent.createChooser(mp3Intent, getString(R.string.audio_file_title)), REQ_CODE_PICK_SOUNDFILE);

and getting uri in onActivityResult by using following code -:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQ_CODE_PICK_SOUNDFILE && resultCode == Activity.RESULT_OK){
        if ((data != null) && (data.getData() != null)){
            Uri mp3FileUri = data.getData();
            // Now you can use that Uri by passing to your MediaPlayer or can use ContentResolver and OutputInputStream() to read MP3 encode byte
            }
        }
}

for more extension and MIME types you can visit here

I think this may help you.

Upvotes: 3

CommonsWare
CommonsWare

Reputation: 1006614

Step #1: Find the MIME type for the file type you want. In the case of MP3, that is audio/mpeg.

Step #2: Pass that MIME type into setType(), instead of audio/*.

Note that ACTION_GET_CONTENT has nothing to do with file extensions, in part because ACTION_GET_CONTENT has nothing to do with files.

Upvotes: 3

Related Questions