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:
- 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? - Is there a more beautiful way of transferring the file descriptor to native code than using the
myNativeCallbackFunction
function approach?
Regards,