android – 从真正的路径获取Uri

前端之家收集整理的这篇文章主要介绍了android – 从真正的路径获取Uri前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个文件的真实路径,如“file:///mnt/sdcard/3dphoto/temp19.jps”
,我怎么能得到像“content:// media / external / images / media / 1”这样的uri?

解决方法

文件路径中转换“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();
        }
    }
}

猜你在找的Android相关文章