【问题标题】:Android Java : How to open a downloaded file using FileProvider in another AppAndroid Java:如何在另一个应用程序中使用 FileProvider 打开下载的文件
【发布时间】:2016-11-01 06:24:58
【问题描述】:

我有以下设置,但是在第三方应用程序中打开文件时,找不到该文件。

下载文件(以字节为单位)后,我将其存储。

public File storeFile(byte[] b, String ref) throws IOException {
      String           path = String.valueOf(ref).replaceAll("/+", "_");
      final File       f    = new File(A.getDir(path, Context.MODE_PRIVATE), "downloads");
      FileOutputStream out  = new FileOutputStream(f);
      out.write(b);
      out.flush();
      out.close();
      return f;
   }

然后尝试阅读并打开它。

try {
    Uri  uri               = Uri.fromFile(storeFile(bytes, ref));
    MimeTypeMap mime       = MimeTypeMap.getSingleton();
    Intent      i          = new Intent(Intent.ACTION_VIEW);
    String      type       = mime.getMimeTypeFromExtension(ext);
    File        imagePath  = new File(getFilesDir(), "downloads");
    File        file    = new File(imagePath, uri.getPath());
    Uri         newUri     = FileProvider.getUriForFile(context, "com.do.app.fileprovider", file);

    i.setDataAndType(uriContent, type);
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    A.startActivity(i);
} catch (IOException e) {
    e.printStackTrace();
}

在清单中

<provider
     android:name="android.support.v4.content.FileProvider"
     android:authorities="com.do.app.fileprovider"
     android:exported="false"
     android:grantUriPermissions="true">
     <meta-data
          android:name="android.support.FILE_PROVIDER_PATHS"
          android:resource="@xml/provider_paths"/>
</provider>

路径

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="cloud_files" path="downloads"/>
</paths>

我似乎找不到我缺少的东西。

【问题讨论】:

  • FileProvider.getUriForFile()。它恢复正常吗?请告诉uri.toString()的值。

标签: java android android-fileprovider


【解决方案1】:
File        imagePath  = File(getFilesDir(), "downloads");

这是一个完全不同的目录

 File       f    = new File(A.getDir(path, Context.MODE_PRIVATE), "downloads");

只需比较imagePath.getAbsolutePath() 和f.getAbsolutePath();

您最好不要构造相同的路径或File 实例两次,而是使用一个变量。

更新。

我现在看到你的代码更乱了。

Uri  uri               = Uri.fromFile(storeFile(bytes, ref));
Uri         newUri     = FileProvider.getUriForFile(context, "com.do.app.fileprovider", file);

您根本没有使用uri 或newUri,而是使用contentUri。为什么有两个/三个尿?换一个。

Uri uri  = FileProvider.getUriForFile(context
        , "com.do.app.fileprovider"
        , storeFile(bytes, ref));

然后将带有 setDataAndType() 的 uri 放入使用的意图中。

【讨论】:

  • 好吧,清理了一下。现在我有这个错误: IllegalArgumentException : Failed to find configured root that contains /data/data/com.do.app/imagename.jpg/downloads at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile
  • 你构建了一个不可能的路径,文件名后面有一个文件夹名!你没看见吗?而且你没有使用我建议的代码。
  • storeFile() 将抛出 IOException。但是您没有看到它,因为您的代码一团糟。调用时ref参数的值是多少?
猜你喜欢
  • 1970-01-01
  • 2017-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-16
相关资源
最近更新 更多