你应该去选择2.不要试图自己做所有事情。询问系统是否有任何可以打开文件的应用程序,如果没有这样的应用程序存在,通知用户没有应用程序来打开该文件。您也可以提供指向可能打开相关文件的应用程序的链接。
使用此方法的重要部分是您需要MIME类型的文件,因为系统会根据所提供的类型做出决定。此外,您可能需要一个内容提供商,以便其他应用程序可以实际打开沙箱中的文件。幸运的是,框架的确提供了File Provider只是为了这种情况。如果您没有将文件存储在应用程序目录中,则不需要提供者。
的代码看起来是这样的
File yourFile; //expecting the file to exist
String extension; //expecting the file extension (pdf, doc, ...) to exist
String mimetype; //may be null. You may obtain the mimetype from the server request in the http Content-Type header.
if (mimetype == null || mimetype.trim().isEmpty()) {
//mimetype does no exist, try to guess mimetype from the extension
mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
}
if (mimetype == null || mimetype.trim.isEmpty()) {
//don't know what the mime type is. All we know is that it is a file we want to open.
mimetype = "file/*";
}
Intent openFileIntent = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(yourFile)), mimetype);
if (openFileIntent.resolveActivity(getPackageManager()) != null) {
this.startActivity(openFileIntent);
} else {
Toast.makeText(this, R.string.no_application_can_open_file, Toast.LENGTH_SHORT).show();
}
但我的应用程序是所有有关文件,如果用户已去到另一个应用程序来查看我提供他不会是打败链接中的文件目的? –
不是。您仍在提取并显示指向用户的链接。这是应用程序的工作,它应该做得很好。为其他应用程序委派显示链接内容是这类用例的推荐方式。看看文件管理器等其他应用程序。你很少会找到一个能够完成所有工作的实现。 – GPuschka