【发布时间】:2011-10-30 12:53:19
【问题描述】:
我有一个文件的真实路径,例如“file:///mnt/sdcard/3dphoto/temp19.jps” ,我怎样才能得到像“content://media/external/images/media/1”这样的uri?
【问题讨论】:
-
似乎与stackoverflow.com/questions/5657411/… 相关,您能提供上下文吗?
标签: android
我有一个文件的真实路径,例如“file:///mnt/sdcard/3dphoto/temp19.jps” ,我怎样才能得到像“content://media/external/images/media/1”这样的uri?
【问题讨论】:
标签: android
在文件路径中转换您的“file://...”,使用以下代码找到项目的 id,然后将其附加到提供程序 URI。此外,根据文件扩展名,使用正确的提供程序(例如 MediaStore.Video.Media.EXTERNAL_CONTENT_URI 或 MediaStore.Image.Media.EXTERNAL_CONTENT_URI)
/**
* Given a media filename, returns it's id in the media content provider
*
* @param providerUri
* @param appContext
* @param fileName
* @return
*/
public long getMediaItemIdFromProvider(Uri providerUri, Context appContext, String fileName) {
//find id of the media provider item based on filename
String[] projection = { MediaColumns._ID, MediaColumns.DATA };
Cursor cursor = appContext.getContentResolver().query(
providerUri, projection,
MediaColumns.DATA + "=?", new String[] { fileName },
null);
if (null == cursor) {
Log.d(TAG_LOG, "Null cursor for file " + fileName);
return ITEMID_NOT_FOUND;
}
long id = ITEMID_NOT_FOUND;
if (cursor.getCount() > 0) {
cursor.moveToFirst();
id = cursor.getLong(cursor.getColumnIndexOrThrow(BaseColumns._ID));
}
cursor.close();
return id;
}
有时 MediaProvider 不会在将一个媒体文件添加到设备存储后立即刷新。您可以使用此方法强制刷新其记录:
/**
* Force a refresh of media content provider for specific item
*
* @param fileName
*/
private void refreshMediaProvider(Context appContext, String fileName) {
MediaScannerConnection scanner = null;
try {
scanner = new MediaScannerConnection(appContext, null);
scanner.connect();
try {
Thread.sleep(200);
} catch (Exception e) {
}
if (scanner.isConnected()) {
Log.d(TAG_LOG, "Requesting scan for file " + fileName);
scanner.scanFile(fileName, null);
}
} catch (Exception e) {
Log.e(TAG_LOG, "Cannot to scan file", e);
} finally {
if (scanner != null) {
scanner.disconnect();
}
}
}
【讨论】:
我的文件浏览器活动有同样的问题...但是您应该知道文件的 contenturi 仅支持媒体存储数据,例如图像、音频和视频...。我为您提供从选择中获取图像内容 uri来自 sdcard 的图像....试试这个代码...也许它对你有用...
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
【讨论】:
另一种简单的方法:
File file = new File(Path);
Uri uri = Uri.fromFile(file);
【讨论】: