0

I'm following this code to delete an apk file before downloading another one and then installing it

String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
String fileName = getResources().getString(R.string.apkname) + ".apk";
destination += fileName;
final Uri uri = Uri.parse("file://" + destination);

File file = new File(destination);
if (file.canRead()) {
    if (file.delete()) {
        Toast.makeText(getApplicationContext(), "File deleted", Toast.LENGTH_LONG).show();
    }
}

I'm finding the file, so I get to file.delete() and then I get the toast message, but when I check in downloads, the file is still there and I end up with multiple files with the same name, I can still use them with no issues, so it's like file.delete() did absolutely nothing.

For the record, I have WRITE_EXTERNAL_STORAGE permission in the manifest AND I request it in runtime too since I'm using sdkversion 25.

What's wrong?

Thanks in advance

1 Answers1

0

Try this solution I have tested...

        String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
        String fileName = getResources().getString(R.string.apkname) + ".apk";
        destination += fileName;

        try {
            File file = new File(destination);
            if (file.canRead()) {

                boolean mDeleleFile = file.delete();
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(destination))));
                if (mDeleleFile) {
                    Toast.makeText(getApplicationContext(), "File deleted", Toast.LENGTH_LONG).show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

I have reference from How to delete a file from SD card?

Community
  • 1
  • 1
rockstar
  • 587
  • 4
  • 22