【发布时间】:2019-10-24 05:20:40
【问题描述】:
我正在从本机 C++ 代码读取和写入文件和目录。获取文件访问的标准方法是使用 Java 中的存储访问框架,然后使用本机代码中的文件描述符(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");
}
从onActivityResult返回的Uri可以被存储并重新获取,这样我们就不必每次都提示用户(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);
但是有些位置(例如app.package/files)可以在没有 SAF 的情况下访问:
- 有没有一种方法可以确定是否可以在没有 SAF 的情况下访问文件/目录,并且没有过去
onActivityResult结果中存储的 Uri? - 有没有比使用
myNativeCallbackFunction函数方法更漂亮的方式将文件描述符传输到本机代码?
问候,
【问题讨论】:
标签: android android-ndk file-access android-10.0 storage-access-framework