Search code examples
androidandroid-5.0-lollipopandroid-sdcardandroid-filedocumentfile

Saving files to SD card on Android Lollipop


Android 5 introduce new API for working with SD-card. If you want to write files into some directory on the SC-card, y need get access to it. As far as I know, it could be done in this way:

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 42);

and then:

public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (resultCode == RESULT_OK) {
        Uri treeUri = resultData.getData();

        getActivity().getContentResolver().takePersistableUriPermission(treeUri,
                    Intent.FLAG_GRANT_READ_URI_PERMISSION |
                    Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
     }
}

This code launch folder picker, and when folder is picked it requires permissions on the folder by it's Uri.

But is it possible to get permissions on exact directory by it's path? Without using folder picker. I meant that I know directory, which I want get access, and I don't want to launch Folder Picker, because it will confuse user.

How to open DocumentFile without user interaction?


Solution

  • It's impossible. User should choose directory using android's file picker. The only way to get access to folder is using:

    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); startActivityForResult(intent, 42);

    Because file is provided by Storage Access Framework DocumentsProvider. Actually it could return some Uri from 3-rd party app, which is not real file, but some entity, which 3-rd party app present as file.