1

In my application I can take a photo and save it with this code:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

imageCaptureUri = Uri.fromFile(new File(context.getExternalFilesDir(null),
                        "tmp_image_" + String.valueOf(System.currentTimeMillis()) + ".jpg"));

intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageCaptureUri);
intent.putExtra("return-data", true);

I tried to delete the file from my SD card with this code:

File f = new File(imageCaptureUri.getPath());            

if (f.exists() == true) 
{
    boolean state = f.delete();
    Toast.makeText(context, "" + state, Toast.LENGTH_LONG).show();
}

The output of the Toast is true but the file is not deleted on the SD card. I tested this on Android KitKat but it should work on older android versions too. Do you have any ideas why I can't delete the photo?

I used android.permission.WRITE_EXTERNAL_STORAGE in my manifest file.

Cilenco
  • 6,951
  • 17
  • 72
  • 152
  • use a try catch block around your code and see if there are any exceptions. – Sagar Pilkhwal Sep 03 '14 at 16:04
  • No exception is throwen – Cilenco Sep 03 '14 at 16:09
  • I found out that it works on Android 4.2 so I guess that it is a problem from Android KitKat. There the API has changed a bit but I think it is all right? – Cilenco Sep 03 '14 at 16:16
  • yes, for android 4.4+ we can only delete package specific files. doucmentation says _"Apps must not be allowed to write to secondary external storage devices, except in their package-specific directories as allowed by synthesized permissions."_ – Sagar Pilkhwal Sep 03 '14 at 16:16
  • 1
    Yes that's right but I store the file in `getExternalFilesDir`. Do I have to save it in an other location? This is the package-specific directories isn't it? – Cilenco Sep 03 '14 at 16:17
  • check [this post](http://stackoverflow.com/a/23761450/3326331). – Sagar Pilkhwal Sep 03 '14 at 16:19
  • Okay thank you. But look [here](http://source.android.com/devices/tech/storage/) in the third paragraph. With the code from above I store the file in this directory but nevertheless it does not work. – Cilenco Sep 03 '14 at 16:25

2 Answers2

0

With some quick searching, i see that occasionally a call to System.gc() is occasionally necessary. Call System.gc() after your f.delete()

r2DoesInc
  • 3,759
  • 3
  • 29
  • 60
  • 1
    Thank you for that but I tested it and the file is still there. – Cilenco Sep 03 '14 at 16:10
  • I found out that it works on Android 4.2 (without System.gc) so I guess that it is a problem from Android KitKat. Do you have any other ideas? – Cilenco Sep 03 '14 at 16:16
0

KitKat have some changes on how apps can or not access files. Even in the external storage.

Because that's a temp file, I suggest you to relocate it to your own app space like context.getCacheDir instead. That will probably work.

Budius
  • 39,391
  • 16
  • 102
  • 144