Restricting selectable file types via intent in Android
Based on above answer and similar thread i developed a working solution. i am sharing code snippet , so it will be easy to use.
How to filter or select file for specific file types using intents.
Code
public static Intent getCustomFileChooserIntent(String ...types){
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// Filter to only show results that can be "opened"
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, types);
return intent;
}
Sample file types Constants
public static final String DOC = "application/msword";
public static final String DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
public static final String IMAGE = "image/*";
public static final String AUDIO = "audio/*";
public static final String TEXT = "text/*";
public static final String PDF = "application/pdf";
public static final String XLS = "application/vnd.ms-excel";
Usage
// i passed string values, you can pass a array of string too.
Intent intent = getCustomFileChooserIntent(DOC, PDF, IMAGE);
startActivityForResult(intent, 101);
Pass multiple MIME types separate with |
like
i.setType("image/*|application/pdf|audio/*");
or create an array of MIME types like
String[] mimetypes = {"image/*", "application/*|text/*"};
and pass it as
i.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);