您好我有一个代码大小约为1 / 2mb的应用。该应用程序包含一个用于显示多个页面的webview。因此我的缓存最终为2,5mb。不够多但足够了。如何清除onDestroy上的缓存?
THX!
答案 0 :(得分:9)
将此代码放入onDestroy()以获取清除应用缓存
@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();
}
答案 1 :(得分:2)
如上面提供的链接所示,您可以获取缓存目录,然后将其与子项一起删除,以清除缓存,如下所示:
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();
}