how to make intent.setType for pdf,xlsx and txt file android?

前端 未结 7 2060
情话喂你
情话喂你 2020-12-04 21:48

I want to choose only pdf, xlsx and txt file from storage but intent.setType can do only one file(eg.txt file only (or) pdf file only). Is it possible to get all three files

相关标签:
7条回答
  • 2020-12-04 22:41

    @Fatehali Asamadi's way is OK, but need to add something for appropriate use. For Microsoft documents both (.doc or .docx), (.ppt or .pptx), (.xls or .xlsx) extensions are used. To support or browse these extensions you need to add more mimeTypes.

    Use below method to browse documents where REQUEST_CODE_DOC is requestCode for onActivityResult(final int requestCode, final int resultCode,final Intent data) @Override method.

    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);
    
    }
    

    You can get clear concept and add your required mimeTypes from Here

    0 讨论(0)
提交回复
热议问题