gpt4 book ai didi

android - 从文件路径获取 MediaStore 内容 Uri?

转载 作者:行者123 更新时间:2023-11-29 14:56:48 25 4
gpt4 key购买 nike

我有一个应用程序可以列出 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;
}

基本上,MediaStoreDATA 列(或您正在查询的任何子部分)存储文件路径,因此您可以使用该信息来查看它上。

关于android - 从文件路径获取 MediaStore 内容 Uri?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5045965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com