0

I am trying to make a program that deletes files programmatically. My program has the write & read permissions.

The code can be oversimplified to this:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    File asd = new File("/storage/emulated/0/Pictures/IMG_20210228_165109.jpg ");
    System.out.println(asd.exists());//true
    System.out.println(asd.setWritable(true));//true
    System.out.println(asd.canWrite());//false
    System.out.println(asd.delete());//false
}

Yes, I hardcoded the example but you get the point, the real program is not hardcoded. Both the example and the real program fail to delete files like this.

I tried on Android Emulator of android studio and my phone. Both times the result was same - true on exists() and setWritable() but false on canWrite() and delete().

Why is that the case? (The android version of my phone is 10, and emulator's is 11.)

Shazniq
  • 423
  • 4
  • 16
  • 2
    We have not had write access to arbitrary locations on [removable storage](https://commonsware.com/blog/2019/10/11/storage-situation-removable-storage.html) since Android 4.4. – CommonsWare Feb 28 '21 at 14:23
  • @CommonsWare The android file system is so confusing. What about the /storage/emulated/0/Pictures/IMG_20210228_165109.jpg format? Is this accessible? Thank you. – Shazniq Feb 28 '21 at 14:37
  • 1
    "Is this accessible?" -- to be honest, I do not remember whether you can delete files from there on Android 11+. – CommonsWare Feb 28 '21 at 14:42
  • 1
    how did you get the file permission through menifest or run time? Check out this thread. https://stackoverflow.com/questions/55908308/android-write-to-file-permission-denied And then let us know the update. – MD Ruhul Amin Feb 28 '21 at 14:55

1 Answers1

1

Three things.

Request read and write permission in manifest.

Add code to let the user confirm those permissions at run time.

For an Android 10 device request legacy external storage in manifest.

On an Android 11 device an app can only delete its own files.

blackapps
  • 8,011
  • 2
  • 11
  • 25