我试图清除我自己的应用程序的缓存后我退出她 类似这个应用程序 - >管理应用程序 - >“我的应用程序” - >清除缓存 ,我已经试过这段代码,但不起作用。我把它放在main_acitivty.java中如何清除应用程序缓存在android退出
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' _before_'super.onDestroy',不是吗? –
@MattClark感谢您的回复我想在退出我的应用程序后清除缓存 – MrMR
我明白了,并且您已经在退出事件的代码路径中。 'super.onDestroy'将清除代码上游的所有对象。您需要先清除缓存,然后再允许该应用完全退出。这是我的假设,您的缓存实际上并未被清除,因为应用程序在您的代码运行之前退出。此外,当您复制其他人的代码1:1时,[至少将其归入作者](http://stackoverflow.com/a/18200934/1790644)。 –