Home > Blockchain >  How to delete a folder on Android 11?
How to delete a folder on Android 11?

Time:02-25

I have a doubt, how I can delete a folder on Android 11 (or 10)?

Have much answers here on Stack how to do it, but nothing of worked.

This code worked for me on Android 5:

 public static boolean deleteDir(File dir) {
      if (dir.isDirectory()) {
           String[] children = dir.list();
           for (int i=0; i<children.length; i  ) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                     return false;
                }
           }
      }

      // The directory is now empty so delete it
      return dir.delete();
 }

On newest versions of Android it not work. I noticed that there are applications that can to do this, so I imagine it is possible. Any answer about it?

CodePudding user response:

Android has done much to change its permission models around file access since Android 10 and 11. The preferred approach is to use Scoped Storage APIs.

Many of the old file read/write permissions are on life support and will no longer work. If they do continue to work, then must justify to Google why you need them, and then go through a security approval by Google. You will only be granted approval if you app is classified as a file browser application, or the like.

Basically, the new model is to use Android's file browsers to gain access to read/write/update a particular file that the user selects, and defer the rest of the file management to Google's first-party applications. The access you get is based on what the user selected in the first-party file browser. You are then handed a URI back to your application with the proper permissions to perform the intended action, such as read/write/etc...

You may find this video useful:

https://www.youtube.com/watch?v=RjyYCUW-9tY

CodePudding user response:

Have you tried Context.deleteFile() ?

getApplicationContext().deleteFile(filename);
  • Related