Android: Getting a file URI from a content URI?

JMRboosties picture JMRboosties · Apr 14, 2011 · Viewed 142.1k times · Source

In my app the user is to select an audio file which the app then handles. The problem is that in order for the app to do what I want it to do with the audio files, I need the URI to be in file format. When I use Android's native music player to browse for the audio file in the app, the URI is a content URI, which looks like this:

content://media/external/audio/media/710

However, using the popular file manager application Astro, I get the following:

file:///sdcard/media/audio/ringtones/GetupGetOut.mp3

The latter is much more accessible for me to work with, but of course I want the app to have functionality with the audio file the user chooses regardless of the program they use to browse their collection. So my question is, is there a way to convert the content:// style URI into a file:// URI? Otherwise, what would you recommend for me to solve this problem? Here is the code which calls up the chooser, for reference:

Intent ringIntent = new Intent();
ringIntent.setType("audio/mp3");
ringIntent.setAction(Intent.ACTION_GET_CONTENT);
ringIntent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(ringIntent, "Select Ringtone"), SELECT_RINGTONE);

I do the following with the content URI:

m_ringerPath = m_ringtoneUri.getPath();
File file = new File(m_ringerPath);

Then do some FileInputStream stuff with said file.

Answer

Jason LeBrun picture Jason LeBrun · Apr 14, 2011

Just use getContentResolver().openInputStream(uri) to get an InputStream from a URI.

http://developer.android.com/reference/android/content/ContentResolver.html#openInputStream(android.net.Uri)