1
The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external 
storage on a device. Apps must not be allowed to write to secondary external storage 
devices, except in their package-specific directories as allowed by synthesized 
permissions. Restricting writes in this way ensures the system can clean up files
when applications are uninstalled.

However i've seen that it is possible to gain write priviledges at runtime (Proof of concept: Total Commander) using the System File Explorer to select a folder for which write is allowed after the folder selection is complete. However I can't seem to find an example of how to implement this. Any help with that? A screenshot of the folder selection that I'm reffering to is shown below.

enter image description here

Anonymous
  • 4,470
  • 3
  • 36
  • 67

1 Answers1

4

I guss i ll answer my own question for future visitors...

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, 1);


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    boolean finish = true;
    boolean selectionWasCorrect = false;
    if(resultCode==RESULT_OK){ 
         //Take persistant permission. This way you can modify the selected folder ever after a device restart.
         Uri treeUri = data.getData();
         int takeFlags = data.getFlags()  & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
         getContentResolver().takePersistableUriPermission(treeUri, takeFlags); 
    }
}

All these are applicable only from KIT_KAT and above

Anonymous
  • 4,470
  • 3
  • 36
  • 67
  • Please note, this is only available from LOLLIPOP and not KIT_KAT. – Distjoy Apr 28 '17 at 10:43
  • FYI. This gives you permanent access permission to the selected directory. To read/write files on SD, see https://stackoverflow.com/questions/36862675/android-sd-card-write-permission-using-saf-storage-access-framework – Leon Oct 15 '17 at 07:13