android - 如何根据文件类型打开合适的应用程序

标签 android file

我试图打开文件夹中的文件。这个想法是提供下载的应用程序可以打开的最大类型的 office 文件 + pdf。所以我下载了 14 种不同的文件类型示例,例如 .docx、.ppt、.pdf 等。 我有 WPS 办公室作为应用程序来运行这些。但问题是,当我使用下面的代码时,文件会直接在 WPS 办公应用程序中打开。如果我更改为 target.setDataAndType(Uri.fromFile(open), "application/pdf"); 然后它会显示 adobe reader 和 WPS office 作为选项。有什么方法可以让我在不特别指定/pdf 或/msword 的情况下获得打开文件的最佳选择?这样我就可以根据输入类型获得可能的应用列表。

Intent target = new Intent(Intent.ACTION_VIEW);
                target.setDataAndType(Uri.fromFile(open), "application/msword");
                target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

                Intent intent = Intent.createChooser(target, "Open File");
                try {
                    startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    // Instruct the user to install a PDF reader here, or
                    // something
                    Toast.makeText(
                            getApplicationContext(),
                            "Please install proper document reader in your device to open this file",
                            Toast.LENGTH_SHORT).show();
                } 

最佳答案

我假设您想使用文件扩展名打开应用程序,而不指定应用程序/*

 File file = new File(filePath);
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String ext = MimeTypeMap.getFileExtensionFromUrl(file.getName());
    String type = map.getMimeTypeFromExtension(ext);

    if (type == null)
        type = "*/*";

    Intent intent = new Intent(Intent.ACTION_VIEW);
    Uri data = Uri.fromFile(file);

    intent.setDataAndType(data, type);

    startActivity(intent);

这应该得到扩展并打开“最好的”应用程序

关于android - 如何根据文件类型打开合适的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25051765/

相关文章:

c++ - 从 .h 和 .cpp 文件定义纯虚函数会产生链接器错误?

java - 无法使用套接字发送大文件

java - 任务 ':app:mergeExtDexDebug' 执行失败

android - 播放youtube视频全屏webview崩溃

java - Android中LocationListener的SettableFuture block 事件

bash - while 循环在附加文件 bash 中中断到早期

javascript - 每次事件后创建目录

c# - Linq - 使用 not "IN"运算符从文本文件中选择非重复行

android - ExceptionInInitializerError 异常

java - Android:双击会在不应该缩小位图图像的情况下缩小......?