【问题标题】:Convert a Uri into a non-Uri android将 Uri 转换为非 Uri android
【发布时间】:2012-09-12 12:45:06
【问题描述】:

我有这样的路径:

content://media/external/audio/media/7181

是这样获得的 String mSelectedPath = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI + "/"; 然后我将歌曲 ID 附加到此。

我想把它转换成/mnt/sdcard/..这样的路径

我该怎么做?

【问题讨论】:

    标签: android file parsing uri converter


    【解决方案1】:

    Android 的媒体数据库将文件路径存储在DATA 列中。您可以通过

    阅读
    long id = 7181;
    Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
    
    ContentResolver cr = getContentResolver();
    String[] projection = { MediaColumns.DATA };
    String selection = null;
    String[] selectionArgs = null;
    String sortOrder = null;
    Cursor c = cr.query(uri, projection, selection, selectionArgs, sortOrder);
    String path = null;
    if (c != null) {
        if (c.moveToFirst()) {
            path = c.getString(0);
        }
        c.close();
    }
    Log.d("XYZ", "Path of " + id + " is:" + path);
    

    但就像@CommonsWare 所说的那样(尤其是在未来的 android 版本上)可能没有您可以访问的文件,甚至根本没有路径,这意味着您获得的路径可能一文不值。

    幸运的是,ContentProvider 允许您使用 IO 流读取数据,前提是提供者实现了该功能(IIRC 实现了该功能)。所以你可以读取Uri 代表的数据,如下例所示。

    long id = 7181;
    Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
    
    ContentResolver cr = getContentResolver();
    InputStream is = null;
    try {
        is = cr.openInputStream(uri);
        is.read(); // replace with useful code.
    } catch (FileNotFoundException e) {
        Log.w("XYZ", e);
    } catch (IOException e) {
        Log.w("XYZ", e);
    } finally {
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                // ignored
            }
    }
    

    【讨论】:

      【解决方案2】:

      你没有。可能没有文件(例如,字节存储在数据库的 BLOB 列中,内容表示流),或者文件位于您的进程无法访问的位置。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-13
        • 1970-01-01
        • 2014-07-15
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        • 2016-02-13
        相关资源
        最近更新 更多