Having trouble implementing ACTION_OPEN_DOCUMENT to my project
In onActivityResult()
, call takePersistableUriPermission()
on a ContentResolver
, passing in the Uri
that you got along with the mode flag(s) that indicate what access you want (read, write, both).
To handle permission results overide onRequestPermissionsResult as below
@Override
public void onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case General.REQUESTPERMISSION:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//reload my activity with permission granted or use the features that required the permission
} else {
Messenger.makeToast(getContext(), R.string.noPermissionMarshmallow);
}
break;
}
}
and to persist the permission implement as shown below in your onActivityResult method
@Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if ok user selected a file
if (resultCode == RESULT_OK) {
Uri sourceTreeUri = data.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getContext().getContentResolver().takePersistableUriPermission(sourceTreeUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
}
}