我正在尝试在另一个查看器(例如图库或 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 文件,或 Adobe Reader,如果它是 PDF 等),并且 Activity 正确打开。但是,他们无法访问该文件。为什么他们不能访问该文件?
最佳答案
与第三方应用共享流的官方方式是通过 FileProvider
,其中这些流来自您应用的内部存储。 FileProvider
是 ContentProvider
的一个实现,它负责为您共享这些流。
FileProvider
将适用于大多数编写良好的 Android 应用程序。有时,您共享或发送内容的应用程序会因 FileProvider
而失败,因为编写该应用程序的人很懒惰,并假设所有内容都来自 MediaStore
,您可以随时映射文件的 Uri
。 That's not the case .为了帮助与那些损坏的客户端兼容,我有 a LegacyCompatCursorWrapper
您可以将其融入您的 FileProvider
,它提供了 Stefan Rusek's solution for this problem 的固定实现.
关于Android 外部应用程序无法访问应用程序的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30286920/