2015-11-01 47 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