Reputation: 976
Hi I've got an app with a code size of approximately 1/2mb. The app includes a webview for showing several pages. My cache therefore ends up at 2,5mb. Not much but enough. How can I clear my cache onDestroy?
Thx!
Upvotes: 2
Views: 8359
Reputation: 2321
put this code in onDestroy() for clear app cache
@Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
// Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
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;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
Upvotes: 9
Reputation: 37
As given in the link provided above, you can get the cache directory and then delete it along with its children to clear the cache as follows:
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
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();
}
Upvotes: 2