Hyndrix
Hyndrix

Reputation: 4452

Determine existing file access permissions on Android Q

I am reading and writing to files and directories from native C++ code. The standard way for getting file access is to use the Storage Access Framework in Java and then use the file descriptor in the native code (https://developer.android.com/training/data-storage/files/media#native-code):

// Called from native code:
public void requestFile() {
    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    startActivityForResult(intent, CREATE_REQUEST_CODE);
}

public native myNativeCallbackFunction(int fd, ...);

public void onActivityResult(int requestCode,
        int resultCode, Intent resultData) {

    Uri uri = resultData.getData();
    ParcelFileDescriptor parcelFd = resolver.openFileDescriptor(uri, "r");
    int fd = parcelFd.detachFd();
    myNativeCallbackFunction(fd, "other information identifying the file such as the file name");
}

The returned Uri from onActivityResult can be stored and re-taken so that we do not have to prompt the user each time (https://developer.android.com/guide/topics/providers/document-provider#permissions):

final int takeFlags = intent.getFlags()
            & (Intent.FLAG_GRANT_READ_URI_PERMISSION
            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(uri, takeFlags);

But there are some locations (such as app.package/files for instance) which can be accessed without the SAF:

  1. Is there a way to determine if a file/directory can be accessed without SAF and without having the stored Uri from a past onActivityResult result?
  2. Is there a more beautiful way of transferring the file descriptor to native code than using the myNativeCallbackFunction function approach?

Regards,

Upvotes: 0

Views: 567

Answers (1)

blackapps
blackapps

Reputation: 9292

   intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

Remove that line. It makes no sense. You cannot grant anything there.

getFilesDir(), getExternalFilesDir() and getExternalFilesDirs() are the places where you can still use the classic File classes.

Further: In principle you dont have to store the obtained uris as with getPermanentUriPermissions() you can always see them.

But if you have more than one permission you will not know which one is for which. So storing self is needed too.

Upvotes: 1

Related Questions