Reputation: 279
i'm trying to clear cache of my own application After i exit her similar this Apps --> Manage Apps --> "My App" --> Clear Cache ,i already tried this code but doesn't work. i put it in 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();
}
Upvotes: 0
Views: 3242
Reputation: 641
I would recommend don't do such long things before app closing.
It can visually slow down you app closing or can be ignored by system at all.
If you use this files temporarily than the best time for deleting is after end of using files.
If you use this files to improve speed of some things in your app then it is normal to provide cache managing directly to user. For example simple button "Clear cache" in settings.
Also as mentioned by @Nicolas Maltais onDestroy is not always called. Furthemore in some cases onStop also isn't always called.
But if you would like to do it only in this way you also should know that app is closing. If there are more than one activity you should count open/closed activity. The simpliest way is to implement Activity Lifecycle callback and register for them in Application class. In this implementation you should increment counter variable in onCreate and decrease in onDestroy. And you can determine app closing as zero counter after decreasing in onDestroy.
int mCounter;
void onCreate() {
++mCounter
}
void onDestroy() {
--mCounter;
if (mCounter == 0) {
// app is closing
}
}
Upd: You should store this callback in application class or as Singleton.
Upvotes: 1