17

In Android 11, with the scoped storage enforcement the requestLegacyExternalStorage flag will no longer work for accessing files in external storage. With

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

declared in the manifest file, as well as this permission being granted at runtime by the user, the following code used to be able to read the file, but it won't be able to in Android 11. file at /sdcard/Documents/my_confi_file.json

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()
}

In Android 11, is it still possible to read a file from this directory(/sdcard/Documents/) and how to do it?

The use case is that the device and app are not public and there is no user privacy concerns. The owner of the device and app would like to upload a file to this directory (/sdcard/Documents/) in the device and the app will be reading the content from this file.

s-hunter
  • 24,172
  • 16
  • 88
  • 130

1 Answers1

0

Use this before requesting

Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        startActivity(intent);

To get.

        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));
Gopal Reddy
  • 36
  • 1
  • 5