【问题标题】:Getting file path from uri on emulator从模拟器上的uri获取文件路径
【发布时间】:2015-04-09 18:41:11
【问题描述】:

我想从 Uri 获取视频的文件路径。以下方法在真机测试时效果很好,但是在模拟器上测试时失败(返回 null)。

    public String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Video.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return null;
    }

在模拟器上从uri获取文件路径的正确方法是什么?

【问题讨论】:

    标签: android storage


    【解决方案1】:

    以下方法在真机测试时效果很好

    仅在您尝试过的设备上,并且仅适用于您尝试过的应用。特别是在 Android 4.4+ 上,您的方法将不可靠。那是因为a Uri is not a file。在旧版本的 Android 上,对于来自 MediaStoreUri,您的方法可能有效。

    现在,不要尝试获取Uri 的文件。使用Uri,使用ContentResolver 上的方法获取InputStream、MIME 类型等。

    在模拟器上从uri获取文件路径的正确方法是什么?

    没有。不必有与 Uri 关联的文件路径,更不用说您的应用能够使用 Java 文件 I/O 访问的路径了。

    【讨论】:

    • 如果我需要获取文件路径以便将其存储在数据库中并播放与之关联的视频怎么办?在这种情况下,正确的方法是什么?
    • @Mantas:你想要的通常不会奏效。在 Android 4.4 及更高版本上,您可以try takePersistableUriPermission() 获得持久权限,然后将Uri(以String 形式)保存在您的数据库中。但是没有要求视频将来仍然存在,也没有要求 Uri 一直有效,尤其是在 Android 4.4 之前。
    【解决方案2】:

    正如 CommonsWare 所提到的,Uri 不是文件。处理 Uri 的一般方法是使用输入流并将内容保存为文件(假设这是您要查找的内容)。我通常做的是

    1. 获取与 Uri 关联的元数据(以获取标题/数据类型/大小)
    2. 通过输入流获取内容以将其作为文件保存在设备上。

    查看此页面上的“检查文档元数据”和“获取输入流”:https://developer.android.com/guide/topics/providers/document-provider.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-05
      • 2011-03-25
      相关资源
      最近更新 更多