Android APIv29 FileNotFoundException EACCES(权限被拒绝)
构建targetSdkVersion v29时无法访问存储.
I'm not able to access storage when building for targetSdkVersion v29.
这是我的gradle配置:
Here is my gradle configuration:
compileSdkVersion 29
buildToolsVersion "29.0.2"
...
minSdkVersion 15
targetSdkVersion 29
请注意,为targetSdkVersion 28
进行构建时,已授予WRITE_EXTERNAL_STORAGE
权限,并且相同的设置也可以正常工作.
NOTE that WRITE_EXTERNAL_STORAGE
permission is granted and the same setup works fine when building for targetSdkVersion 28
.
这是我的实现方式
val outputFolder = File(baseFolder + File.separator + "Output Folder")
if (!outputFolder.exists()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Files.createDirectory(outputFolder.toPath()) //This allways returns false with targetSdkVersion 29
} else {
if (!outputFolder.mkdirs()) {
Log.e("SaveRaw", "Unable to create folder for audio recording")
}
}
}
outputFile = File("$baseFolder/Output Folder/$filename")
try {
fileOutputStream = FileOutputStream(outputFile)
} catch (e: FileNotFoundException) {
e.printStackTrace() // allways throwing exception here, even if Output Folder exists
}
这是一个例外:
W/System.err: java.io.FileNotFoundException: /storage/emulated/0/Chirp Auto Tester/2019_10_17 10:44:43.raw: open failed: EACCES (Permission denied)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
at java.io.FileOutputStream.<init>(FileOutputStream.java:235)
at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
希望任何人都有答案,我在这里想念什么?
Hope anyone has an answer, what am I missing here?
更新:
这是baseFolder
的来源.请注意,getExternalStorageDirectory
是已弃用的方法.
Here is where baseFolder
comes from. Note that getExternalStorageDirectory
is a deprecated method.
val baseFolder: String = if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Environment.getExternalStorageDirectory().absolutePath
} else {
context.filesDir.absolutePath
}
谢谢
SAF 或媒体存储.目前,您可以通过在清单中的application标签内添加以下内容来继续使用所用的内容:
Starting with Android 11 the storage permission is getting revoked and developers would need to consider alternative ways of accessing the storage they need either through SAF or Media Store. For the time being, you can carry on using what you’re using by adding the following in your manifest within the application tags:
android:requestLegacyExternalStorage="true"
您可能要考虑将minSDK更改为19,然后使用getExternalFilesDir()
获取不需要任何权限的路径.
You might want to consider changing your minSDK to 19 and use getExternalFilesDir()
to get a path that doesn’t require any permissions.