问题
I need to find a way how to clear the data which my application stores in cache.Basically I am using Fedor\'s ( Lazy load of images in ListView ) lazy list implementation and I want to clear the cache automatically when I have for example 100 images loaded.Any ideas how to do that?
EDIT: Code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list=(ListView)findViewById(R.id.list);
adapter=new LazyAdapter(this, mStrings);
list.setAdapter(adapter);
deleteCache(this);
adapter.notifyDataSetChanged();
}
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();
}
回答1:
this will delete 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();
}
回答2:
I hope this helps you in getting further
public static void trimCache(Context context) {
File dir = context.getCacheDir();
if(dir!= null && dir.isDirectory()){
File[] children = dir.listFiles();
if (children == null) {
// Either dir does not exist or is not a directory
} else {
File temp;
for (int i = 0; i < children.length; i++) {
temp = children[i];
temp.delete();
}
}
}
}
回答3:
you can call system service clearApplicationUserData() ( working only for >= KitKat version )
so you can do a check for version and then everything will go fine :) here is the code :
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
((ActivityManager) getActivity().getSystemService(Context.ACTIVITY_SERVICE))
.clearApplicationUserData();
}
回答4:
If using Apache Commons IO, you can accomplish this with a single line (excluding try-catch):
try {
FileUtils.deleteDirectory(context.getCacheDir());
} catch (IOException e) {
// Do some error handling
}
回答5:
Discard old adapter and attach the listview to a new instance of the adapter (listview will lose scroll position, though). Example:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
m_adapter = new MyAdapter(this);
final ListView listView = (ListView) getView()
.findViewById(R.id.my_list);
listView.setAdapter(m_adapter);
}
}
来源:https://stackoverflow.com/questions/6898090/how-to-clear-cache-android