【问题标题】:Android external app can't access app's filesAndroid 外部应用程序无法访问应用程序的文件
【发布时间】:2015-05-17 12:36:19
【问题描述】:

我正在尝试在另一个查看器(例如图库或 PDF 查看器)中打开我在一个应用上下载的文件。这是我保存文件的方式:

FileOutputStream fos = null;

try {
      fos = from.openFileOutput(name, Context.MODE_WORLD_READABLE);
      fos.write(data); //data is my byte[]
      fos.flush();
      fos.close();
}catch...

// at this point the file IS written to the path. I can SFTP to my [rooted] device
// and can download the file, it's valid, it opens on my computer.

File outputFile = new File(from.getFilesDir().getAbsolutePath() + "/" + name);
if(!outputFile.exists()){
  //show some error message
  //we are NOT entering here, just a programmatic check that it exists.
  return;
}
String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension("." + extension.toUpperCase()); //extension is file extension as String
//if it doesn't work, I set it manually to some valid one by looking at the extension myself.
Intent intent = new Intent();
intent.setDataAndType(Uri.parse(outputFile.getAbsolutePath()), mime);
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

我可以看到打开的对话框(它是正确的,例如,为 PNG 文件显示画廊,或者如果是 PDF 等,则显示 Adob​​e Reader),并且活动正确打开。但是,他们无法访问该文件。为什么他们无法访问该文件?

【问题讨论】:

  • MODE_WORLD_READABLE 已被弃用,从一开始就不是一个好主意。 FLAG_GRANT_READ_URI_PERMISSION 与文件权限无关,而是与ContentProvider 权限有关。我建议您添加a FileProvider 来提供文件。
  • 您将应用程序存储在应用程序的私有内存中。我认为您必须将文件存储在 SD 卡中,以便其他应用程序可以访问它。内存,您的应用程序私有,其他应用程序无法访问。
  • @CommonsWare 我最终得到了FileProvider,谢谢。

标签: android android-4.0-ice-cream-sandwich


【解决方案1】:

与第三方应用共享流的官方方式是通过FileProvider,这些流来自您应用的内部存储。 FileProviderContentProvider 的一个实现,它为您处理共享这些流。

FileProvider 适用于大多数编写良好的 Android 应用程序。有时,您共享或发送内容的应用程序会以FileProvider 失败,因为编写该应用程序的人很懒,并认为所有内容都来自MediaStore,您始终可以将Uri 映射到文件。 That's not the case。为了帮助与那些损坏的客户端兼容,我有 a LegacyCompatCursorWrapper,您可以将其融合到您的 FileProvider 中,它提供了 Stefan Rusek's solution for this problem 的固定实现。

【讨论】:

    【解决方案2】:

    有几种方法可以在 Android 中存储数据,正如我所见,默认情况下,内部存储器中的存储对于您的应用来说是“私有的”(我认为您正在这样做),因此它不会那么简单从另一个应用程序访问。

    解决方案似乎是使用“外部存储器”(可以是移动或可移动 SD 卡的内部存储)
    Here you have the official guide to Android Storage,您可以在其中找到此类存储的一些示例:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 2018-05-15
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多