我们已经尝试解决这个问题几个小时了,最终决定回到StackOverflow。
我们有一个应用程序,它从服务器下载PDF文件到应用程序的缓存目录,然后使用数据包管理器打开它。当然,它通过grantUriPermission()
来为所有可用的包授予读(和写)权限。
虽然它在大多数设备上运行良好,但今天我们遇到了一个默认安装POLARIS Office 5作为PDF查看器的设备。
每当我们打开文件时,Polaris只显示一个消息,说“无法打开此文档”。
我应该说,当尝试通过Acrobat Reader打开文件时,它运行良好。 此外,当我们将文件从缓存目录复制到外部目录(使用Android的文件管理器),然后手动在Polaris中打开它时,它也可以正常工作。
我们本来想放弃它,但由于Polaris是许多设备上的默认查看器,我们真的很想解决这个问题。
以下是代码 -
public void onDownloadDone(String filepath) {
// Set a file object that represents the downloaded file
File file = new File(filepath);
// Set an intent for the external app
Intent intent = new Intent(Intent.ACTION_VIEW);
// Get mime type of the downloaded file
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(filepath);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
intent.setType(mimeType);
// Look for installed packges according to the file's mime type
PackageManager pm = context.getPackageManager();
Uri contentUri = FileProvider.getUriForFile(context, "myapp.fileprovider", file);
// Set the file uri in the intent
intent.setData(contentUri);
// Give permissions to the file to each external app that can open the file
List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
for (ResolveInfo externalApp: activities){
String packageName = externalApp.activityInfo.packageName;
context.grantUriPermission(packageName, contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
// Start the activities (or launch the menu) if any activity exists
if (activities.size() > 0){
context.startActivity(intent);
} else {
System.out.println("Warning!!! No app for file " + filepath);
}
}
非常感谢!
FileProvider
作为ContentProvider
的实现方式吗?此外,您使用grantUriPermissions()
的原因是什么,而不是使用FLAG_GRANT_READ_URI_PERMISSION
呢? - CommonsWare