在Android11中,使用requestLegacyExternalStorage标志作用域存储强制执行将不再适用于访问外部存储中的文件。使用
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>在清单文件中声明的,以及用户在运行时授予的这个权限,下面的代码曾经能够读取该文件,但是它不能在/sdcard/Documents/my_confi_file.json的Android11.file中读取。
try {
var fileContent = ""
val file = File("/sdcard/Documents/my_confi_file.json")
val fileInputStream = FileInputStream(file)
val size = fileInputStream.available()
val buffer = ByteArray(size)
fileInputStream.read(buffer)
fileContent = String(buffer, Charset.forName("UTF-8"))
fileInputStream.close()
} catch (e: IOException) {
e.printStackTrace()
}在Android 11中,仍然可以从这个目录(/sdcard/Documents/)读取一个文件吗?
用例是,该设备和应用程序不公开,也不涉及用户隐私问题。设备和应用程序的所有者希望将文件上载到设备中的这个目录(/sdcard/Documents/),应用程序将从该文件中读取内容。
发布于 2022-08-16 02:48:44
在请求之前使用此方法
Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);为了得到。
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+"/FolderName/"+new_filename+"/");
File[] allfiles = null;
allfiles = file.listFiles();
Log.i(TAG, String.valueOf(allfiles.length));https://stackoverflow.com/questions/60795079
复制相似问题