Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear Cache in Android Application programmatically

Tags:

android

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

like image 615
Rizwan Ahmed Avatar asked May 28 '14 09:05

Rizwan Ahmed


People also ask

How do I clear all app cache on Android?

Open Settings, and then swipe to and tap Apps. Select or search for the app you want to clear. Tap Storage, and then tap Clear cache. Note: The only way to clear the cache on every app at the same time would be to perform a factory reset on your phone.

How do I automatically clear app cache?

Tap Clear data to clear app data and cache. You'll then have to select whether you want to clear all data associated with the app or just its cache. Clearing data will automatically clear the cache of the app as well.


2 Answers

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;     } } 
like image 123
dharam Avatar answered Oct 01 '22 06:10

dharam


Kotlin has an one-liner

context.cacheDir.deleteRecursively() 
like image 22
Fintasys Avatar answered Oct 01 '22 04:10

Fintasys