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

时间:2015-05-17 12:36:20

标签: 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文件显示图库,如果是PDF等,则显示Adobe Reader),并且活动正确打开。但是,他们无法访问该文件。为什么他们无法访问该文件?

2 个答案:

答案 0 :(得分:1)

有几种方法可以在Android中存储数据,正如我所看到的,默认情况下,内部存储器中的存储是"私有"到你的应用程序(因为我认为你正在做)所以从另一个应用程序访问它不会那么简单。

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

答案 1 :(得分:1)

与第三方应用共享流的官方方式,即来自应用内部存储的流来自FileProviderFileProviderContentProvider的一种实现,可以为您分享这些流。

FileProvider适用于大多数编写良好的Android应用。有时,您分享或发送内容的应用会因FileProvider而失败,因为撰写该应用的人很懒,并认为所有内容都来自MediaStore,您始终可以映射Uri到一个文件。 That's not the case。为了帮助与这些破碎的客户端兼容,我a LegacyCompatCursorWrapper可以将Stefan Rusek's solution for this problem添加到您的FileProvider中,该Spring Security JWT提供了{{3}}的预制实现。