47

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 by coding intent.setType() and Is there a way to do?

Here is some of my code.

  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

    }
}
2

7 Answers 7

64

@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

5
  • 1
    I'm unable to see documents in-app while using this code. Can you help
    – Pawandeep
    Apr 16, 2019 at 17:36
  • My app supports Kitkat and above. So, I only use the first logic condition. However, somehow, it shows everything instead of just the intended ones. I am doubting about this line intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");. Doesn't it make it shows everything? Sep 12, 2019 at 10:05
  • what is the purpose of that line ? intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "/");. Jun 9, 2020 at 9:11
  • 1
    spent too much time looking for the docx Mime type "application/vnd.openxmlformats-officedocument.wordprocessingml.document", which I needed to for CrossFilePicker.Current.PickFile() allowedTypes parameter. Thanks :)
    – chri3g91
    Jul 1, 2020 at 9:58
  • use this code to detect mimetype File file = new File(filePath); String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()); String mimeType = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); Feb 3, 2021 at 11:05
21
intent.setType("image/*|application/pdf|audio/*");

Maybe this is what you want.

3
  • 9
    Is this documented somewhere? When I tried combining multiple types like this, the intent didn't select any file type.
    – arlomedia
    Jan 15, 2019 at 20:47
  • yeah its more clear but doesnt work with '|' operator, i have tried and didnt work. Nov 17, 2021 at 23:31
  • yes, same here. not working with "|" Jul 3, 2022 at 14:28
12

You should to check this link http://www.androidsnippets.com/open-any-type-of-file-with-default-intent.html. Also read through Mime Type.

This is how I have implemented for any file or selected mime type file

String[] mimeTypes =
{"image/*","application/pdf","application/msword","application/vnd.ms-powerpoint","application/vnd.ms-excel","text/plain"};

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"), 0);
8

It looks like you just want to see if those intents can be resolved. This might be a better approach:

 private void showFileChooser() {

    Intent intentPDF = new Intent(Intent.ACTION_GET_CONTENT);
    intentPDF.setType("application/pdf");
    intentPDF.addCategory(Intent.CATEGORY_OPENABLE);

    Intent intentTxt = new Intent(Intent.ACTION_GET_CONTENT);
    intentTxt.setType("text/plain");
    intentTxt.addCategory(Intent.CATEGORY_OPENABLE);

    Intent intentXls = new Intent(Intent.ACTION_GET_CONTENT);
    intentXls.setType("application/x-excel");
    intentXls.addCategory(Intent.CATEGORY_OPENABLE);

    PackageManager packageManager = getPackageManager();

    List activitiesPDF = packageManager.queryIntentActivities(intentPDF,
    PackageManager.MATCH_DEFAULT_ONLY);
    boolean isIntentSafePDF = activitiesPDF.size() > 0;

    List activitiesTxt = packageManager.queryIntentActivities(intentTxt,
    PackageManager.MATCH_DEFAULT_ONLY);
    boolean isIntentSafeTxt = activitiesTxt.size() > 0;

    List activitiesXls = packageManager.queryIntentActivities(intentXls,
    PackageManager.MATCH_DEFAULT_ONLY);
    boolean isIntentSafeXls = activitiesXls.size() > 0;

    if (!isIntentSafePDF || !isIntentSafeTxt || !isIntentSafeXls){

        // Potentially direct the user to the Market with a Dialog

    }

}

References:

http://developer.android.com/training/basics/intents/sending.html

How do I determine if Android can handle PDF

6

The simple solution is

   Intent gallery=new Intent();
        gallery.setType("application/*");
        gallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(gallery,pick);

Note: pick is int variable.

3

You can use Intent.ACTION_OPEN_DOCUMENT,

Each document is represented as a content:// URI backed by a DocumentsProvider, which can be opened as a stream with openFileDescriptor(Uri, String), or queried for DocumentsContract.Document metadata.

All selected documents are returned to the calling application with persistable read and write permission grants. If you want to maintain access to the documents across device reboots, you need to explicitly take the persistable permissions using takePersistableUriPermission(Uri, int).

Callers must indicate the acceptable document MIME types through setType(String). For example, to select photos, use image/*. If multiple disjoint MIME types are acceptable, define them in EXTRA_MIME_TYPES and setType(String) to */*.

For the more details, please refer this link

http://developer.android.com/reference/android/content/Intent.html#ACTION_OPEN_DOCUMENT

Note that this is only available on API Level 19+.

0

Here's the kotlin way:

  val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
  val mimeType = arrayOf(
    "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"
  ).joinToString("|")
  intent.type = mimeType
  intent.addCategory(Intent.CATEGORY_OPENABLE)
  val chooserIntent = Intent
    .createChooser(intent, fragment.getString(R.string.str_attachfile_chooser_message))
  launcher.launch(chooserIntent)

Launcher can be as:

val launcher = registerForActivityResult(StartActivityForResult()) { result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
        val intent = result.data
        // handle stuff here
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.