问题
I'am trying to open multiple files relative to a json configuration file in android 4.4 (api level 19), I used
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType({mime});
this.startActivityForResult(intent, {code});
to let the user find te configuration file, and from there open multiple files that I know the path from the config file.
But i get
Caused by: java.lang.SecurityException:
Permission Denial: reading com.android.providers.downloads.DownloadStorageProvider
uri content://com.android.providers.downloads.documents/document/raw:/storage/emulated/0/Download/{relative file}
requires that you obtain access using ACTION_OPEN_DOCUMENT or related APIs
I dont want to use user interfaces to open the other files, so I tried adding the following permissions without getting any results
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS "/>
I would rather have the files separated and not in a blob or a zip file
回答1:
ACTION_OPEN_DOCUMENT
only gives you access to exactly the file (or files, if you use EXTRA_ALLOW_MULTIPLE) that the user selects.
You can use ACTION_OPEN_DOCUMENT_TREE to allow the user to select a folder - you'll then get access to all files in that folder (and their subfolders).
回答2:
If you need to let the user choose multiple files from a file chooser, you can do the following:
It's part of my app, you can adjust it for your needs. This works starting from API 18
private void openFileChooser() {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
i.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(i, REQUEST_CODE_DOC_ALL_FILES);
}
Then here is how you get the selected Uris:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_DOC_ALL_FILES && resultCode == Activity.RESULT_OK) {
if (data == null || (data.getData() == null && data.getClipData() == null)) {
Toast.makeText(getContext(), R.string.invalid_source, Toast.LENGTH_SHORT).show();
return;
}
//get result after user action (selecting files) and transform it into array of Uris
Uri[] uriPaths;
if (data.getData() != null) { // only one uri was selected by user
uriPaths = new Uri[1];
uriPaths[0] = data.getData();
} else if (data.getClipData() != null) {
int selectedCount = data.getClipData().getItemCount();
uriPaths = new Uri[selectedCount];
for (int i = 0; i < selectedCount; i++) {
uriPaths[i] = data.getClipData().getItemAt(i).getUri();
}
}
}
来源:https://stackoverflow.com/questions/53246026/android-open-inputstream-from-relative-uri-to-action-open-document