Skip to content

Instantly share code, notes, and snippets.

@chnouman
Last active September 7, 2017 09:08
Show Gist options
  • Select an option

  • Save chnouman/14ac2f90876c74472671ff225692b949 to your computer and use it in GitHub Desktop.

Select an option

Save chnouman/14ac2f90876c74472671ff225692b949 to your computer and use it in GitHub Desktop.
public long getDirSize(File dir){
long size = 0;
for (File file : dir.listFiles()) {
if (file != null && file.isDirectory()) {
size += getDirSize(file);
} else if (file != null && file.isFile()) {
size += file.length();
}
}
return size;
}
public static String readableFileSize(long size) {
if (size <= 0) return "0 Bytes";
final String[] units = new String[]{"Bytes", "kB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}
public void clearCache() {
long size = 0;
size += getDirSize(this.getCacheDir());
size += getDirSize(this.getExternalCacheDir());
Toast.makeText(this, " Cache Cleared "+readableFileSize(size), Toast.LENGTH_SHORT).show();
File cache = getCacheDir();
//cache.;
//clear SD cache
File[] files = getCacheDir().listFiles();
for (File f : files) {
size = size + f.length();
f.delete();
}
clearApplicationData();
}
public void clearApplicationData()
{
File cache = getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()){
String[] childeren = appDir.list();
for (String s : childeren){
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 && dir.isDirectory()){
String[] childeren = dir.list();
for (int i = 0; i < childeren.length; i++) {
boolean success = deleteDir(new File(dir, childeren[i]));
if (!success)
{
return false;
}
}
}
return dir.delete();
}
@chnouman

chnouman commented Sep 7, 2017

Copy link
Copy Markdown
Author

Clear Cache code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment