问题
I am developing a app in which there is a button which will clear all the data (which will include files, databases, shared preferences) related with this app. any one can let me know how to clear application data by code.
回答1:
call clearApplicationData
to delete app's data:
/**
* Call this method to delete any cache created by app
* @param context context for your application
*/
public static void clearApplicationData(Context context) {
File cache = context.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
File f = new File(appDir, s);
if(deleteDir(f))
Log.i(TAG, String.format("**************** DELETED -> (%s) *******************", f.getAbsolutePath()));
}
}
}
private 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();
}
来源:https://stackoverflow.com/questions/9110096/android-clean-application-data