Reputation: 4452
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:
onActivityResult
result?myNativeCallbackFunction
function approach?Regards,
Upvotes: 0
Views: 567
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