【问题标题】:Determine existing file access permissions on Android Q确定 Android Q 上现有的文件访问权限
【发布时间】: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 的情况下访问:

  1. 有没有一种方法可以确定是否可以在没有 SAF 的情况下访问文件/目录,并且没有过去 onActivityResult 结果中存储的 Uri?
  2. 有没有比使用myNativeCallbackFunction 函数方法更漂亮的方式将文件描述符传输到本机代码?

问候,

【问题讨论】:

    标签: android android-ndk file-access android-10.0 storage-access-framework


    【解决方案1】:
       intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
    

    删除该行。这没有道理。你不能在那里授予任何东西。

    getFilesDir(), getExternalFilesDir() and getExternalFilesDirs() 是您仍然可以使用经典 File 类的地方。

    进一步:原则上你不必像getPermanentUriPermissions()那样存储获得的uris,你总是可以看到它们。

    但是,如果您拥有多个权限,您将不知道哪个权限用于哪个权限。所以也需要存储self。

    【讨论】:

      猜你喜欢
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      • 1970-01-01
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多