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

    }
}
Halo
  • 729
  • 1
  • 8
  • 18
  • you should look at http://stackoverflow.com/a/33117677/5597641 – Dani Akash Feb 24 '17 at 07:19
  • 1
    Possible duplicate of [how to pick few type of file via intent in android?](http://stackoverflow.com/questions/33117592/how-to-pick-few-type-of-file-via-intent-in-android) – Dani Akash Feb 24 '17 at 07:30

7 Answers7

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

mavrosxristoforos
  • 3,573
  • 2
  • 25
  • 40
Zia
  • 1,204
  • 1
  • 11
  • 25
  • 1
    I'm unable to see documents in-app while using this code. Can you help – Pawandeep Apr 16 '19 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? – Yusril Maulidan Raji Sep 12 '19 at 10:05
  • what is the purpose of that line ? intent.setType(mimeTypes.length == 1 ? mimeTypes[0] : "*/*");. – moumenShobakey Jun 09 '20 at 09: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 01 '20 at 09: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); – user2094075 Feb 03 '21 at 11:05
22
intent.setType("image/*|application/pdf|audio/*");

Maybe this is what you want.

Rishav
  • 3,818
  • 1
  • 31
  • 49
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);
mavrosxristoforos
  • 3,573
  • 2
  • 25
  • 40
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

Community
  • 1
  • 1
Daniel Nugent
  • 43,104
  • 15
  • 109
  • 137
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.

Sam
  • 241
  • 3
  • 7
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+.

rdonuk
  • 3,921
  • 21
  • 39
King of Masses
  • 18,405
  • 4
  • 60
  • 77
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
    }
}
vishnu benny
  • 998
  • 1
  • 11
  • 15