Amith
Amith

Reputation: 93

Clearing Cache in android App Programmatically

I need one help regarding cache memory in my android app. I am Running server (android) in a device. I want to do clear cache of that app programmatically. I have database in that server. Based on that database my client operations are going on. So I don't want it (Database) to get effected. I just want to clear cache not to clear data. Please help me with this.

Upvotes: 7

Views: 19925

Answers (3)

Md Hussain
Md Hussain

Reputation: 409

Code for clearing the cache:

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        if (dir != null && dir.isDirectory()) {
            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();
    }
    return false;
}

Upvotes: 3

Aown Raza
Aown Raza

Reputation: 2023

public class HelloWorld extends Activity {

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle *) {
      super.onCreate(*);
      setContentView(R.layout.main);
   }

   @Override
   protected void onStop(){
      super.onStop();
   }

   //Fires after the OnStop() state
   @Override
   protected void onDestroy() {
      super.onDestroy();
      try {
         trimCache(this);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void trimCache(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 {
         return false;
      }
   }

Upvotes: 6

Merthan Erdem
Merthan Erdem

Reputation: 6058

On Kotlin you can just call

File(context.cacheDir.path).deleteRecursively()

Upvotes: 6

Related Questions