Search code examples
javaandroidfileondestroy

How to delete file when application is closed


I want to delete a file when my app is closed. I perform the deletion in the onDestroy method of my activity. But when I check to see if the file is deleted, after closing the app, the file is still there.

Here's what my code looks like so far:

@Override
protected void onDestroy() {

    File file = new File(Environment.getExternalStorageDirectory().getPath(), "fileName.txt");
    if(file.exists()){
        file.delete();
    }

    super.onDestroy();
}

EDIT: Asked to show snippet of code regarding the creation of a temp file:

try {
        file = File.createTempFile(Environment.getExternalStorageDirectory().getPath(), fileName);
    } catch (IOException e) {
        e.printStackTrace();
    }

Solution

  • You should not rely on onDestroy method to be called (the system can interrupt your process before the lifecycle will reach this stage). I would suggest you use temporary folders to keep such a file, but it is still your responsibility to keep the size of temp files within reasonable limits (~1 mb).


    UPDATE (in relation to the temp-file snippet)

    You are trying to provide a full path to ExternalStorageDirectory as a file-name prefix. But this approach is a bit different. The File.createTempFile function does nothing except creating a file in a special temp-file directory using random name. Thus, it is still our responsibility to provide a temp-folder, letting the system know that this file is appropriate to delete:

    public File getTempFile(Context context, String url) {
        File file;
        try {
            String fileName = Uri.parse(url).getLastPathSegment();
            file = File.createTempFile(fileName, null, context.getCacheDir());
        catch (IOException e) {
            // Error while creating file
        }
        return file;
    }
    

    The cachedDir is internal storage, which means that other apps cannot write files here, so you should implement FileProvider to provide a URI of your temporary file.