For a new feature I’m adding to Runr I needed to get access to audio files. Now, I don’t want to really have some buggy implementation that is dependent on placing files in specific folders on the SD Card. I just want to get all the Audio Files off the card then display them in a spinner or something.
This is where Content Providers come in; more specifically, those provided by the Android OS itself. I won’t go into too much detail of making a content provider, but they essentially allow you to make access to certain data public so other can use it. In my case, I want to know what audio files are on disk but don’t care about where they are and having to find them. Android has taken care of this for us, and we are going to take advantage of it.
In order to use the content provider we need to set establish a few things first:
- We need to make a call to the appropriate URI to get access to the right content provider
- We will need to specify what data we want from our request (which columns we want)
- If there is any limitation on what kind of selection we are doing
- What kind of ordering we want our data to be in
/*
* We only care about content that is stored on the SD Card, so we will only query
* the content provider that provides us with external audio files.
*/
URI audioURI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
// Set up the projection so that we reduce the data we fetch to only the stuff we need
// In our case we only want to get the Title, Author and the audio data
String[] projection = new String {
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.DATA
};
String selectionString = "WHERE " + MediaStore.Audio.Media.ARTIST + "=?";
String[] selectionArgs = new String[] {"Lady GaGa"};
String sortOrder = MediaStore.Audio.Media.ARTIST + " ASC";
// Run the query
Cursor cursor = managedQuery(audioURI, projection, selectionString, selectionArgs, sortOrder);
// Make sure we have data to actually iterate through
if( cursor.moveToFirst() ){
while( !cursor.isAfterLast() ){
// Have the cursor determine what index the Title and Artist information is stored at
String title = cursor.getString( cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String artist = cursror.getString( cursor.getColumnIndex( MediaStore.Audio.Media.ARTIST));
Log.i("ContentProviderExample", "Found: " title + " by " + artist);
}
} else {
Log.i("ContentProviderExample", "No Audio files!");
}
This code would be running in an activity of course which gives you access to the managedQuery function.
Anyway, I hope this little blog post provides a bit of information on how to determine what audio files are available on the users Android device.
References: