我正在研究app并将数据保存在sharedpreference和cache中,我希望只清除应用程序的缓存而不是共享首选项数据。我该怎么做?这是我的代码
public 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) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
}
}
} public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
System.out.println("Directory not null");
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
答案 0 :(得分:1)
当我运行应用程序时,它清除了本地内存的所有数据
这是因为这一行:
File appDir = new File(cache.getParent());
摆脱它。删除对appDir
的所有引用。
如果您要删除getCacheDir()
,则删除getCacheDir()
,而不是其他内容,例如getParent()
的{{1}}。
答案 1 :(得分:0)
删除缓存目录
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();
}
您需要权限
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>