从实际路径获取乌里 [英] Get Uri from real Path

查看:167
本文介绍了从实际路径获取乌里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个文件的真实路径文件:///mnt/sdcard/3dphoto/temp19.jps ,我怎么能得到URI喜欢的内容://媒体/外部/图片/媒体/ 1?

I have a real path of a file like "file:///mnt/sdcard/3dphoto/temp19.jps" , how can i get the uri like "content://media/external/images/media/1 "?

推荐答案

将您的file:// ......在一个文件路径,找到下面的code项目的ID,然后追加它提供的URI。另外,根据文件扩展名,使用合​​适的供应商(例如MediaStore.Video.Media.EXTERNAL_CONTENT_URI或MediaStore.Image.Media.EXTERNAL_CONTENT_URI)

Transform your "file://..." in a file path, find the id of the item with the following code, and then append it to provider URI. In addition, based on file extensions, use the right provider (for example MediaStore.Video.Media.EXTERNAL_CONTENT_URI or 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不刷新立刻后一个媒体文件被添加到设备存储。您可以强制使用此方法以刷新其纪录:

Sometimes MediaProvider doesn't refresh immediatly after one media file is added to device's storage. You can force to refresh its records using this method:

/**
 * 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();
        }
    }
} 

这篇关于从实际路径获取乌里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆