android 通过Uri获取真实路径,通过路径获取Uri

可以根据不同情况传入不同databaseUri例如查询音频数据MediaStore.Audio.Media.EXTERNAL_CONTENT_URI

或者查询图片数据库MediaStore.Audio.Media.EXTERNAL_CONTENT_URI

public Uri queryUriforAudio(String path,Uri databaseUri) {
        File file = new File(path);
        final String where = databaseUri + "='" + file.getAbsolutePath() + "'";
        Cursor cursor = this.getContentResolver().query(databaseUri, null, where, null, null);
        if (cursor == null) {
            Log.d("uritest", "queryUriforAudio: uri为空 1");
            return null;
        }
        int id = -1;
        if (cursor != null) {
            cursor.moveToFirst();
            if (!cursor.isAfterLast()) {
                id = cursor.getInt(0);
            }
            cursor.close();
        }
        if (id == -1) {
            Log.d("uritest", "queryUriforAudio: uri为空 2");
            return null;
        }
        return Uri.withAppendedPath(databaseUri, String.valueOf(id));
    }

可以根据个人需要写的更灵活一些

public static String getFilePath( final Context context, final Uri uri ) {  
    if ( null == uri ) return null;  
  
    final String scheme = uri.getScheme();  
    String data = null;  
  
    if ( scheme == null )  
        data = uri.getPath();  
    else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {  
        data = uri.getPath();  
    } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {  
        Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );  
        if ( null != cursor ) {  
            if ( cursor.moveToFirst() ) {  
                int index = cursor.getColumnIndex( ImageColumns.DATA );  
                if ( index > -1 ) {  
                    data = cursor.getString( index );  
                }  
            }  
            cursor.close();  
        }  
    }  
    return data;  
} 

你可能感兴趣的:(android,常用代码,代码片段)