2012-09-12 21 views
0

我有這樣一個路徑:轉換一個URI到非開放的安卓

內容://媒體/外部/音頻/媒體/ 7181

那這樣String mSelectedPath = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/"; ,然後得到我將歌曲ID附加到此。

我想將它轉換成路徑如/ mnt/SD卡/ ..

我該怎麼辦呢?

回答

1

Android的媒體數據庫存儲DATA列中文件的路徑。您可以閱讀通過

long id = 7181; 
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id); 

ContentResolver cr = getContentResolver(); 
String[] projection = { MediaColumns.DATA }; 
String selection = null; 
String[] selectionArgs = null; 
String sortOrder = null; 
Cursor c = cr.query(uri, projection, selection, selectionArgs, sortOrder); 
String path = null; 
if (c != null) { 
    if (c.moveToFirst()) { 
     path = c.getString(0); 
    } 
    c.close(); 
} 
Log.d("XYZ", "Path of " + id + " is:" + path); 

但是就像@CommonsWare說,這是可能的,(特別是在未來的Android版本)沒有文件,您可以訪問,甚至沒有路可言,這意味着你可能是毫無價值的路徑。

幸運的是ContentProvider允許您讀取IO流的數據,如果提供者具有該功能(IIRC這樣做)。所以你可以像下面的例子那樣讀取Uri所代表的數據。

long id = 7181; 
Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id); 

ContentResolver cr = getContentResolver(); 
InputStream is = null; 
try { 
    is = cr.openInputStream(uri); 
    is.read(); // replace with useful code. 
} catch (FileNotFoundException e) { 
    Log.w("XYZ", e); 
} catch (IOException e) { 
    Log.w("XYZ", e); 
} finally { 
    if (is != null) 
     try { 
      is.close(); 
     } catch (IOException e) { 
      // ignored 
     } 
} 
1

你不知道。可能沒有文件(例如,字節存儲在數據庫的BLOB列中,內容表示流),或文件位於您的進程無法訪問的位置。