问题
I'm having an issue with an app: (rarely) a user will download the app from the play store but the obb/expansion file will fail to download. If the folder for the obb file is created (Android/obb/my.package.name
), that's fine, I can manually download the obb file without a problem.
However, if the folder for the obb file was not created, attempting to create it with File::mkdir()
or File::mkdirs()
fails (returns false). Attempting to create and write to the obb file without a directory throws a FileNotFoundException
.
File obbFile = new File("path/to/obb/file.obb");
File parent = obbFile.getParentFile();
if (!parent.exists() && !parent.mkdir()) {
// Failed to create directory
}
External read/write permissions are set up and working correctly as we can read/write/create other files/directories with no issue.
I've read How to create a folder under /Android/obb? but the only solution given to that is to drop the target sdk to 22.
Has anyone else come across this and found a solution or workaround?
回答1:
The Context::getObbDir() method allows access to the expansion folder without the usual security rules. I found that, if the folder doesn't exist, getObbDir()
creates it too (You can also double check create it manually with mkdir()
).
Excerpt from the documentation linked above:
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. ...
So the code in the question can become:
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.
}
NOTE: You may need the read/write permissions to access the expansion files within the folder. See the documentation for more info.
来源:https://stackoverflow.com/questions/53830611/is-there-a-way-to-manually-create-the-package-folder-for-an-apks-obb-file