如何在/Android/obb下创建文件夹?

How to create a folder under /Android/obb?

我正在尝试使用扩展文件,但我发现了一个我无法解决的问题。

您似乎可以访问 /Android/obb 文件夹并最终删除 /Android/obb/my.package.name 目录(尝试使用一些文件管理器),但我无法在应用程序中处理这种情况。

如果我让 Google 下载程序库尝试下载扩展文件,它会挂起并出错(对于丢失的文件夹),但如果我重新创建文件夹,它会启动。

奇怪的是,我可以从其他应用程序(我用来查看目录的同一文件管理器)创建文件夹但不能从我的应用程序创建文件夹 !

我试过

File f = new File(Environment.getExternalStorageDirectory(), "Android/obb/my.package.name");
f.mkdirs();

但是没用。

我有清单中的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

我的目标是 api 23 并使用 25 进行编译。

OP 将 Target SDK 降至 22,并能够避免导致该问题的危险权限工作流程。

,但降低 Target SDK 不是一个选项。

Context::getObbDir() 方法允许在没有通常的安全规则的情况下访问扩展文件夹。我发现,如果该文件夹不存在,getObbDir() 也会创建它(您也可以仔细检查并使用 mkdir() 手动创建它)。

上面链接的文档摘录:

Return the primary shared/external storage directory where this application's OBB files (if there are any) can be found. Note if the application does not have any OBB files, this directory may not exist.

This is like getFilesDir() in that these files will be deleted when the application is uninstalled, however there are some important differences:

... Starting in Build.VERSION_CODES.KITKAT, no permissions are required to read or write to the path that this method returns. ...

Starting from Build.VERSION_CODES.N, Manifest.permission.READ_EXTERNAL_STORAGE permission is not required, so don’t ask for this permission at runtime. ...

所以你可以这样做:

File obbDir = getObbDir();

if (null == obbDir) {
    // Storage is not available
} else  if (!obbDir.exists() && !obbDir.mkdir()) {
    // Failed to create directory. Shouldn't happen but you never know.
}

注意:您可能需要 read/write 权限才能访问文件夹中的扩展 文件