【问题标题】:How to get content-scheme Uri from file path?如何从文件路径获取内容方案 Uri?
【发布时间】:2012-08-15 11:21:49
【问题描述】:

我有一种情况,我知道文件的路径,并以这种方式解决它:

File f = new File(Environment.getExternalStorageDirectory(), "image.jpg");

然后从中创建一个 Uri:

Uri uri = Uri.fromFile(f);

但是,这个 Uri 会打印出如下内容:

file://.....

但我想要:

content://.....

“为什么?”。因为有些应用程序对方案敏感,例如 Facebook。如果您在附加图像时将文件方案 Uri 传递给 Facebook,它什么也不做。如果您将内容方案 Uri 传递给同一个图像,它会完美运行。

那么如何通过知道绝对路径或将文件方案 Uri 转换为内容方案 Uri 来获取内容 Uri?

编辑(2012 年 8 月 24 日):最新的 Facebook 应用程序更新“解决”了这个问题,只需删除选择器,只显示图库。您再也无法在 Facebook 中通过意图进行选择了。

【问题讨论】:

    标签: android


    【解决方案1】:

    试试这个'

    Uri uri = Uri.parse(f);
    

    代替Uri uri = Uri.fromFile(f);

    【讨论】:

    • 使用我的文件和 Uri.parse(f.toString()) 我得到“/mnt/sdcard/image.jpg”,这似乎根本没有任何方案。
    【解决方案2】:

    到目前为止,我最好的选择似乎是这种扫描文件的方法,然后返回带有内容方案的 Uri:

    File f = new File(Environment.getExternalStorageDirectory(), "image.jpg");
    
    MediaScannerConnection.scanFile(this, new String[]{f.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
        public void onScanCompleted(String path, Uri contentUri) {
            // TODO: Do something useful with contentUri, which now has content-scheme
        }
    });
    

    【讨论】:

    • 对不起,我看不到上面的代码是如何回答这个问题的。如何将 contentUri 参数的值传递给调用scanFile() 的活动?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2011-03-01
    • 2019-08-17
    • 2014-07-31
    • 1970-01-01
    • 2020-06-10
    相关资源
    最近更新 更多