+-
如何为pdf,xlsx和txt文件android制作intent.setType?
我想从存储中仅选择pdf,xlsx和txt文件,但intent.setType只能执行一个文件(仅限eg.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),(.pt或.pptx),(.xls或.xlsx)扩展名.要支持或浏览这些扩展,您需要添加更多mimeTypes.

使用以下方法浏览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

点击查看更多相关文章

转载注明原文:如何为pdf,xlsx和txt文件android制作intent.setType? - 乐贴网