Android 外部应用程序无法访问应用程序的文件

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

我正在尝试在另一个查看器(例如图库或 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 文件,或 Adob​​e Reader,如果它是 PDF 等),并且 Activity 正确打开。但是,他们无法访问该文件。为什么他们不能访问该文件?

最佳答案

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

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

关于Android 外部应用程序无法访问应用程序的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286920/

相关文章:

android - 如何在整个应用程序生命周期中维护单个 Realm 实例并关闭它?

android - 从 Android Market 更新应用程序后的推荐人

android - 椭圆 Ice Cream Sandwich 添加[

android - 仅在应用程序升级时显示对话框

java - 从 google docs 电子表格中读取数据

java - 无法理解 Fragments/Tabs + ActionBar + swipe (ICS)

android-4.0-ice-cream-sandwich - Novo 7 Paladin 平板电脑 (ICS 4.01) 上的 INSTALL_FAILED_INVALID_APK 错误

java - 三星 Galaxy s3 上的旋转器问题

java - 应用程序不兼容 Ice Cream Sandwich

android - 更改自定义样式资源中的文本样式(粗体)以折叠工具栏布局