根据这个post,我想通过点击导航抽屉中的一些元素来删除程序的缓存。
我已在MainActivity.java
上尝试使用此代码段来删除onNavigationItemSelectedListener
中的缓存,但它无效。
onNavigationItemSelectedListener
方法中的onCreate()
//-------------------------------------- find navigation view
NavigationView navigationView = (NavigationView)findViewById(R.id.xmlNavigation);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
int itemId = menuItem.getItemId();
if(itemId == R.id.star){
===> deleteCache(MainActivity.this);
===> deleteDir(MainActivity.this.getCacheDir());
Toast.makeText(MainActivity.this , "cache is deleted!" , Toast.LENGTH_SHORT).show();
}
menuItem.setChecked(true);
mDrawerLayout.closeDrawers();
//Toast.makeText(MainActivity.this , menuItem.getTitle() , Toast.LENGTH_SHORT).show();
return true;
}
});
}
此代码段来自onCreate()
和MainActivity.java
:
///====================================================== snippet for deleting the cache
public static void deleteCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {}
}
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();
}
///====================================================== #snippet for deleting the cache