android - 如何为 pdf、xlsx 和 txt 文件制作intent.setType android?

标签 android android-intent

我只想从存储中选择 pdf、xlsx 和 txt 文件,但 intent.setType 只能执行一个文件(例如,仅 .txt 文件(或)仅 pdf 文件)。是否可以通过编码intent.setType()来获取所有三个文件,有没有办法?

这是我的一些代码。

  private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("application/pdf");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select txt file"),
                0);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog

    }
}

最佳答案

@Fatehali Asamadi 的方式还可以,但需要添加一些东西以供适当使用。 对于 Microsoft 文档(.doc 或 .docx)、(.ppt 或 .pptx)、(.xls 或 .xlsx)扩展名都使用。要支持或浏览这些扩展,您需要添加更多 mimeType。

使用以下方法浏览文档,其中 REQUEST_CODE_DOC 为 onActivityResult(final int requestCode, final int resultCode,final Intent data) @Override 方法的 requestCode。

private void browseDocuments(){

    String[] mimeTypes =
            {"application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
                    "application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
                    "application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
                    "text/plain",
                    "application/pdf",
                    "application/zip"};

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");
        if (mimeTypes.length > 0) {
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        }
    } else {
        String mimeTypesStr = "";
        for (String mimeType : mimeTypes) {
            mimeTypesStr += mimeType + "|";
        }
        intent.setType(mimeTypesStr.substring(0,mimeTypesStr.length() - 1));
    }
    startActivityForResult(Intent.createChooser(intent,"ChooseFile"), REQUEST_CODE_DOC);

}

您可以从 Here 获得清晰的概念并添加所需的 mimeTypes

关于android - 如何为 pdf、xlsx 和 txt 文件制作intent.setType android?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978581/

相关文章:

android - 差异 : android:background and android:src?

android - 使用构建标记修改 AndroidManifest.xml 会导致 Eclipse 中的无限重建

android - 关闭屏幕后减慢android应用程序的自动关闭过程

java - 根据当前背景更改按钮背景

java - 在 NavigationDrawer 中单击按钮打开 Activity

android - 图像是从画廊上传的,而不是通过 webView 从相机上传的

android - 如何在内部存储上备份 sqlite 数据库

android - 从 onItemClickListener 获取点击 View

android - 如何跟踪 Intent

java - 保留编辑框android代码中的值