Clear Cache in Android Application programmatically

Android

Android Problem Overview


what is the correct way to clear cache in android Application programmatically. I already using following code but its not look work for me

@Override
protected void onDestroy() {
	// TODO Auto-generated method stub
	super.onDestroy();
	clearApplicationData();
}

public void clearApplicationData() {
	File cache = getCacheDir();
	File appDir = new File(cache.getParent());
	if (appDir.exists()) {
		String[] children = appDir.list();
		for (String s : children) {
			if (!s.equals("lib")) {
				deleteDir(new File(appDir, s));
				Log.i("EEEEEERRRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
			}
		}
	}
}
		 
public static boolean deleteDir(File dir) {
	if (dir != null && 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;
			}
		}
	}
		 
	return dir.delete();
}

Image from my android phone

Android Solutions


Solution 1 - Android

If you are looking for delete cache of your own application then simply delete your cache directory and its all done !

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        deleteDir(dir);
    } catch (Exception e) { e.printStackTrace();}
}

public static boolean deleteDir(File dir) {
    if (dir != null && 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;
            }
        }
        return dir.delete();
    } else if(dir!= null && dir.isFile()) {
        return dir.delete();
    } else {
        return false;
    }
}

Solution 2 - Android

Kotlin has an one-liner

context.cacheDir.deleteRecursively()

Solution 3 - Android

The answer from dhams is correct (after having been edited several times), but as the many edits of the code shows, it is difficult to write correct and robust code for deleting a directory (with sub-dirs) yourself. So I strongly suggest using [Apache Commons IO][1], or some other API that does this for you:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS: Also delete the directory returned by context.getExternalCacheDir() if you use that.

To be able to use Apache Commons IO, add this to your build.gradle file, in the dependencies part:

compile 'commons-io:commons-io:2.4'

[1]: https://commons.apache.org/proper/commons-io/ "Apache Commons IO"

Solution 4 - Android

I think you're supposed to place clearApplicationData() before the super.OnDestroy().

Your app can't process any methods when it has been shut down.

Solution 5 - Android

Try this

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    clearApplicationData();
}

public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));
                Log.i("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

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

    assert dir != null;
    return dir.delete();
}

Solution 6 - Android

If you're using kotlin, then:

context.cacheDir.deleteRecursively()

Solution 7 - Android

If you using Android Studio 4.4.2

getCacheDir().delete();

Solution 8 - Android

I am not sure but I sow this code too. this cod will work faster and in my mind its simple too. just get your apps cache directory and delete all files in directory

public boolean clearCache() {
    try {

        // create an array object of File type for referencing of cache files   
        File[] files = getBaseContext().getCacheDir().listFiles();

        // use a for etch loop to delete files one by one
        for (File file : files) {

             /* you can use just [ file.delete() ] function of class File
              * or use if for being sure if file deleted
              * here if file dose not delete returns false and condition will
              * will be true and it ends operation of function by return 
              * false then we will find that all files are not delete
              */
             if (!file.delete()) {
                 return false;         // not success
             }
        }

        // if for loop completes and process not ended it returns true   
        return true;      // success of deleting files

    } catch (Exception e) {}

    // try stops deleting cache files
    return false;       // not success 
}

It gets all of cache files in File array by getBaseContext().getCacheDir().listFiles() and then deletes one by one in a loop by file.delet() method

Solution 9 - Android

Put this code in onStop() method of MainActivity

@Override
protected void onStop() {
    super.onStop();
    AppUtils.deleteCache(getApplicationContext());
}
public class AppUtils {
    public static void deleteCache(Context context) {
        try {
            File dir = context.getCacheDir();
            deleteDir(dir);
        } catch (Exception e) {}
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && 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;
                }
            }
            return dir.delete();
        } else if(dir!= null && dir.isFile()) {
            return dir.delete();
        } else {
            return false;
        }
    }
}

Solution 10 - Android

Using kotlin: to just remove the content:

for (file:File in context?.cacheDir?.listFiles()!!){
             file.delete()
         }

Solution 11 - Android

This code helped me:

// your code
deleteCache(getContext);
//

public void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir.list() != null) {
            deleteDir2(dir);
        }
    } catch (Exception e) { e.printStackTrace();}
}

public boolean deleteDir2(File dir) {
    if (dir.isDirectory()) {
        for (File child : dir.listFiles()) {
            boolean success = deleteDir2(child);
            if (!success) {
                return false;
            }
        }
    }
    return dir.delete();
}

Solution 12 - Android

This code will remove your whole cache of the application, You can check on app setting and open the app info and check the size of cache. Once you will use this code your cache size will be 0KB . So it and enjoy the clean cache.

 if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
                    .clearApplicationUserData();
            return;
        }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRizwan AhmedView Question on Stackoverflow
Solution 1 - AndroiddharamView Answer on Stackoverflow
Solution 2 - AndroidFintasysView Answer on Stackoverflow
Solution 3 - AndroidEirik WView Answer on Stackoverflow
Solution 4 - AndroidDennieView Answer on Stackoverflow
Solution 5 - AndroidMarcos Roberto Nunes LindolphoView Answer on Stackoverflow
Solution 6 - AndroidCiprianView Answer on Stackoverflow
Solution 7 - Androidtoufik sView Answer on Stackoverflow
Solution 8 - AndroidJavidView Answer on Stackoverflow
Solution 9 - AndroidDyno CrisView Answer on Stackoverflow
Solution 10 - AndroidEdwin Paz ss. -View Answer on Stackoverflow
Solution 11 - AndroidArty MorrisView Answer on Stackoverflow
Solution 12 - AndroidGyan Swaroop AwasthiView Answer on Stackoverflow