如何在Android中打开任何扩展名的文件?

10

我有一个应用程序,用户可以上传任何扩展名的文件(例如.png.mp3.txt.pdf.bmp.apk等等)

这些文件会在列表视图中显示。

当用户点击列表视图中的项目时,将调用意图(android.content.Intent.ACTION_VIEW),并应该打开设备中已安装的相应应用程序。

例如

如果用户点击nature.png,则会调用意图并建议类似于Gallery、PS Touch等应用程序(如屏幕截图1所示)

如果用户点击book.pdf,则会调用意图并建议类似于MuPdf、Polaris Office、apv等应用程序(如屏幕截图2所示)

对于 .txt、.pdf、.png 和 .jpg--我通过设置mime类型 intent.setDataAndType(Uri.fromFile(file), mime);解决了这个问题

同时也适用于URL

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(https://www.google.co.in/));

它的功能完美无缺,但对于其他文件扩展名我仍然感到困惑 - 我该怎么做?如何做?

我已经搜索过了,但没有得到令人满意的答案..!

我的问题:

  1. 如何编写代码以处理任何文件扩展名,使其调用安装在设备上的相应应用程序?
  2. 如何在XML中定义自定义文件扩展名?
3个回答

8
以下代码适用于所有文件类型:
try {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Uri.fromFile(file), fileMimeType);
    startActivity(intent);
} catch (ActivityNotFoundException e) {
    // no Activity to handle this kind of files
}

当然,系统中应该有一个活动(Activity),知道如何处理某种类型的文件。希望这可以帮到你。

1
@Egor-谢谢伙计你的帮助...但是如果我上传.apk、.java、.xml或没有扩展名的文件呢?你给出的答案我已经实现了! - TheFlash
@patelpratik 如果您将文件放置在没有扩展名的位置,将会出现ActivityNotFoundException错误。您必须输入文件扩展名以查看文件。否则,您将无法打开文件。 - Dinesh T A

1
指向您问题的第一部分:
try
{
  Intent intent = new Intent(Intent.ACTION_VIEW, uri);
  startActivity(intent);
}
catch (ActivityNotFoundException e)
{
  //tel the user to install viewer to perform this action
}

不需要指定类型,它将从数据URI中获取。

@Dinesh-谢谢伙计...但我还是很困惑...对于MIME类型,设备会自行检测,但对于其他文件exe-如何可能呢? - TheFlash

0
public void openFile() {
    try {
        File file = new File(G.DIR_APP + fileName);
        fileExtension = fileName.substring(fileName.lastIndexOf("."));
        Uri path = Uri.fromFile(file);
        Intent fileIntent = new Intent(Intent.ACTION_VIEW);
        fileIntent.setDataAndType(path, "application/" + fileExtension);
        startActivity(fileIntent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(G.currentActivity, "Cant Find Your File", Toast.LENGTH_LONG).show();
    }

}

这假设有善意,并且文件名始终正确。 - Karuhanga
文件扩展名并不总是与在MIME类型后面的内容匹配。即使对于某些文件类型,'应用程序/'也不能保证是正确的。 - ka3ak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接