在Android应用程序清除缓存编程

问题描述:

什么是明确的Andr​​oid应用程序缓存编程的正确方法。我已经使用以下code,但它不是找我的工作

what is the correct way to clear cache in android Application programmatically. I already using following code but its not look work for me

@Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        clearApplicationData();
}
public void clearApplicationData() {
        File cache = 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("EEEEEERRRRRRROOOOOOORRRR", "**************** 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++) {
        boolean success = deleteDir(new File(dir, children[i]));
        if (!success) {
        return false;
        }
        }
        }

        return dir.delete();
        }

如果您正在寻找自己的应用程序中删除缓存然后只需删除缓存目录及其全部完成!

If you are looking for delete cache of your own application then simply delete your cache directory and its all done !

public static void deleteCache(Context context) {
    try {
        File dir = context.getCacheDir();
        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();
    }
    else if(dir!= null && dir.isFile())
        return dir.delete();
    else {
        return false;
    }
}

和您可能需要以下权限到您的清单文件中添加,以删除其他应用程序缓存

And you may require following permission to add in your manifest file in order to delete cache of other application

<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>