2015-11-01 46 views
1

我正在嘗試檢索文件的Uri。該文件存儲中:從Uri.fromFile(文件)獲得的URI格式不同於通用的URI格式?

/storage/emulated/0/AppName/FileName.png 

如果我用Uri.fromFile(文件),我得到了什麼是

file:///storage/emulated/0/AppName/FileName.jpg 

我想這是什麼格式的東西:

content://media/external/images/media/51128? 

爲什麼不Uri.fromFile(文件)給我這個?我怎麼能得到這個?

+1

- 因爲某些原因,你想要的是來自MediaStore ContentProvider的'Uri'。 「我怎麼能得到這個?」 - 查詢'MediaStore'' ContentProvider'。不管你是否會在那裏找到你的具體文件還有另一個問題。 – CommonsWare

回答

1

Uri.fromFile()給出了一個文件的URI,而不是內容的URI,這是你想要的。

至於如何得到這個,我建議你看到this answer,因爲它涵蓋了從內容URI到內容URI的轉換。

相關的代碼,稍加修改,以符合您的媒體類型(圖片):「爲什麼不Uri.fromFile(文件)給了我這個」

/** 
* Gets the MediaStore video ID of a given file on external storage 
* @param filePath The path (on external storage) of the file to resolve the ID of 
* @param contentResolver The content resolver to use to perform the query. 
* @return the video ID as a long 
*/ 
private long getImageIdFromFilePath(String filePath, 
    ContentResolver contentResolver) { 


    long imageId; 
    Log.d(TAG,"Loading file " + filePath); 

      // This returns us content://media/external/images/media (or something like that) 
      // I pass in "external" because that's the MediaStore's name for the external 
      // storage on my device (the other possibility is "internal") 

    Uri imagesUri = MediaStore.Images.getContentUri("external"); 

    Log.d(TAG,"imagesUri = " + imagessUri.toString()); 

    String[] projection = {MediaStore.Images.ImageColumns._ID}; 

    // TODO This will break if we have no matching item in the MediaStore. 
    Cursor cursor = contentResolver.query(imagesUri, projection, MediaStore.Images.ImageColumns.DATA + " LIKE ?", new String[] { filePath }, null); 
    cursor.moveToFirst(); 

    int columnIndex = cursor.getColumnIndex(projection[0]); 
    imageId = cursor.getLong(columnIndex); 

    Log.d(TAG,"Image ID is " + imageId); 
    cursor.close(); 
    return imageId; 
} 
+0

你什麼時候需要一個文件URI,什麼時候需要一個內容URI?爲什麼有兩種類型的URI? – yeeen