Arun Joshi
Arun Joshi

Reputation: 170

Clear Application cache on exit in android

What I want to do is to clear the cache memory of application on exit of application.

this task i can do manually by this steps.

< Apps --> Manage Apps --> "My App" --> Clear Cache>>

but i wants to do this task by programming on exit of application.. please help me guys..

Thanks in advance..

Upvotes: 14

Views: 60710

Answers (2)

Rod
Rod

Reputation: 117

Just a clarification, the answers work properly except you have to pass the Application context to trimCache instead of the Activity context (to avoid memory leak), since trimCache is an static method.

 @Override
   protected void onDestroy() {
      super.onDestroy();
      try {
         trimCache(getApplicationContext()); //if trimCache is static
      } catch (Exception e) {
        e.printStackTrace();
      }
 }

However, otherwise, you can make trimCache non-static and there is no need to pass any Context.

public void trimCache() {
   try {
     File dir = getCacheDir();
     if (dir != null && dir.isDirectory()) {
        deleteDir(dir);
     }
  } catch (Exception e) {
     // TODO: handle exception
  }
}

Upvotes: 3

Md Abdul Gafur
Md Abdul Gafur

Reputation: 6201

To clear Application Data Please Try this way. I think it help you.

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("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) 
{
    if (dir != null &amp;&amp; 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();
}

Upvotes: 14

Related Questions