【发布时间】:2017-10-01 20:14:18
【问题描述】:
我正在尝试清除我自己的应用程序的缓存在我退出她之后 类似于 应用程序 --> 管理应用程序 --> “我的应用程序” --> 清除缓存 ,我已经尝试过这段代码,但不起作用。我把它放在 main_acitivty.java 中
void onCreate(){
}
..
@Override
protected void onStop(){
super.onStop();
}
//Fires after the OnStop() state
@Override
protected void onDestroy() {
super.onDestroy();
try {
trimCache(this);
} 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();
}
【问题讨论】:
-
我想你会想打电话给
trimCache之前super.onDestroy,不是吗? -
@MattClark 感谢回复我想在退出我的应用程序后清除缓存
-
我明白了,您已经在退出事件的代码路径中。
super.onDestroy将清除代码上游的所有对象。在允许应用程序完全退出之前,您需要清除缓存。我假设您的缓存实际上并未被清除,因为应用程序在您的代码运行之前退出。还有,当你1:1复制别人的代码时,at least attribute it to the author。 -
onDestroy 并不总是被调用,也没有简单的方法可以知道应用程序何时完全关闭。
-
最好使用后台服务/线程来完成这类工作。您可能还想在 onPause 中执行此操作,因为仅当应用程序以某种方式被杀死时才会调用 onDestroy。
标签: android clear-cache