How can I setup an android intent for multiple types of files (pdf, office, images, text) and return a path?
I had a similar problem and spent at least 15 minutes searching for an example of how to actually code the support for EXTRA_MIME_TYPES
Thankfully I did find an example http://android-er.blogspot.co.uk/2015/09/open-multi-files-using.html, tried it, tested it, and it seems to work for my use-case which is to be able to find and load two similar, but not identical, mime-types (for whatever quirky reason the same csv file has one mime-type if I copy it to the device over USB and another if I download it from Google Drive). Here's my code snippet. Presumably you'd add more mime-types in the array of Strings to suit your needs.
public void findReviewsToLoad() {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
String [] mimeTypes = {"text/csv", "text/comma-separated-values"};
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
startActivityForResult(intent, FIND_FILE_REQUEST_CODE);
}
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 here.
private static final int CHOOSE_FILE_REQUEST = 1;
///////////////////////////////////////////////////
public void chooseFile(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
String[] extraMimeTypes = {"application/pdf", "application/doc"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, extraMimeTypes);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(intent, CHOOSE_FILE_REQUEST);
}
/////////////////////////////////////////////////////
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String path = "";
if (resultCode == RESULT_OK) {
if (requestCode == CHOOSE_FILE_REQUEST) {
ClipData clipData = data.getClipData();
//null and not null path
if(clipData == null){
path += data.getData().toString();
}else{
for(int i=0; i<clipData.getItemCount(); i++){
ClipData.Item item = clipData.getItemAt(i);
Uri uri = item.getUri();
path += uri.toString() + "\n";
}
}
}
}
selectedFileTV.setText(path);
}