Search code examples
androidpdfandroid-intent-chooser

How to show PDF file only in intent chooser


I am working on an application in which a user selects a pdf file and then it gets uploaded on firebase. The problem is when a user wants to select a file then other files which are not pdf are also shown. I want to restrict it and want to show pdf files only.

I am using this code to select pdf files only but its showing other files as well.

Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent.createChooser(intent, "Select PDF file"), FILE_CHOOSER);

How can i do it? Any help?


Solution

  • I am using this code to open PDF files only.

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