kumar
kumar

Reputation: 1854

Select specific file types using ACTION_GET_CONTENT and setType or Intent.EXTRA_MIME_TYPES

I want to choose only word, pdf and txt file from storage by using Intent.ACTION_GET_CONTENT. But intent.setType with multiple option is not working (Tried this in android 5.1.1 device and even pdf files are greyed out and cannot select).

intent.setType("application/msword|text/plain|application/pdf");

Is it possible to get all three file types by using just intent.setType()?

Even tried this with Intent.EXTRA_MIME_TYPES.

intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);

Even though EXTRA_MIME_TYPES work and allows to select PDF,word files only and doesnt allow to select other types, it lists the "Gallery" option in menu and allows images/videos to be selected from there(I cannot select image from internal storage). So how can I disable this gallery option (Gallery option is not displayed when I just use intent.setType())?

Upvotes: 5

Views: 6887

Answers (1)

kumar
kumar

Reputation: 1854

The issue is solved using the Intent.ACTION_OPEN_DOCUMENT as suggested by Sam instead of Intent.ACTION_GET_CONTENT.

With ACTION_GET_CONTENT, menu had extra options(marked in red box in the image) which don't honor the MIME types. With ACTION_OPEN_DOCUMENT these options marked in red will not be displayed.

enter image description here

Code:

String[] supportedMimeTypes = {"application/pdf","application/msword"};
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, REQUEST_CODE);

Upvotes: 10

Related Questions