When I try using the code bellow in the onDestroy() method in MainActivity it seams it does not work. What I am doing wrong?
Code:
@Override
protected void onDestroy() {
super.onDestroy();
deleteCacheData();
}
public void deleteCacheData() {
File cacheDir = this.getCacheDir();
File[] files = cacheDir.listFiles();
if (files != null) {
for (File file : files) {
file.delete();
}
}
}
There is two cases with your code:
You can't reliably depends on the case that
onDestroy()method will be called. Because there is no such guarantee that it will always be called by the system. Here the excerpt fromonDestroy()documentation:You should call your
deleteCacheData()before calling thesuper.onDestroy(). So, this is incorrect:this is the correct one: