[英]Get MediaStore content Uri from File path?
我有一個列出MediaStore中所有視頻的應用程序。 (我既需要內部存儲又需要外部存儲)。
基本上,我有兩個游標,它們查詢MediaStore.Video.Media.EXTERNAL_CONTENT_URI和MediaStore.Video.Media.INTERNAL_CONTENT_URI。
然后,我使用MergeCursor合並這些查詢,並使用CursorAdapter在ListView中顯示。
問題是有時我想刪除其中一個視頻,但是我需要“內容Uri”來執行此操作,因為我無法確定所選視頻的存儲方式。
我在MediaStore中擁有視頻和ID的完整文件路徑。
如何從文件路徑/ Uri獲取“內容Uri”?
要回答標題中的問題:
我必須從URI獲取路徑,並從我的應用程序中的路徑獲取URI。 前者:
/**
* Gets the corresponding path to a file from the given content:// URI
* @param selectedVideoUri The content:// URI to find the file path from
* @param contentResolver The content resolver to use to perform the query.
* @return the file path as a string
*/
private String getFilePathFromContentUri(Uri selectedVideoUri,
ContentResolver contentResolver) {
String filePath;
String[] filePathColumn = {MediaColumns.DATA};
Cursor cursor = contentResolver.query(selectedVideoUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
return filePath;
}
后者(我用於視頻,但也可以通過用MediaStore.Audio(等)替換MediaStore.Video來用於音頻或文件或其他類型的存儲內容):
/**
* 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 getVideoIdFromFilePath(String filePath,
ContentResolver contentResolver) {
long videoId;
Log.d(TAG,"Loading file " + filePath);
// This returns us content://media/external/videos/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 videosUri = MediaStore.Video.Media.getContentUri("external");
Log.d(TAG,"videosUri = " + videosUri.toString());
String[] projection = {MediaStore.Video.VideoColumns._ID};
// TODO This will break if we have no matching item in the MediaStore.
Cursor cursor = contentResolver.query(videosUri, projection, MediaStore.Video.VideoColumns.DATA + " LIKE ?", new String[] { filePath }, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
videoId = cursor.getLong(columnIndex);
Log.d(TAG,"Video ID is " + videoId);
cursor.close();
return videoId;
}
基本上, MediaStore
的DATA
列(或您要查詢的子部分)存儲文件路徑,因此您可以使用該信息來查找它。
回答我自己的問題:)
找到一種簡單而簡單的方法來查找路徑的存儲方式:**
if(selectedVideoPath.indexOf(Environment.getExternalStorageDirectory().getPath()) == 0)
{
getContentResolver().delete(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
MediaStore.Video.Media._ID + "=" + videoId,
null);
}
else {
getContentResolver().delete(MediaStore.Video.Media.INTERNAL_CONTENT_URI,
MediaStore.Video.Media._ID + "=" + videoId,
null);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.