首页 > 解决方案 > Android清除缓存以编程方式不起作用

问题描述

我正在尝试以编程方式清除我的应用程序的数据和缓存。请在下面找到相同的代码。

   public static void deleteCache(Context context) {
        try {

            File cache = context.getApplicationContext().getCacheDir();
            File appDir = new File(cache.getParent());
            Log.d(TAG,appDir.getAbsolutePath());
            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 *******************");
                    }
                }
            }

            File cache2= context.getApplicationContext().getExternalCacheDir();
            appDir = new File(cache2.getParent());
            Log.d(TAG,appDir.getAbsolutePath());
            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 *******************");
                    }
                }
            }

            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
                File cache1 = context.getApplicationContext().getDataDir();
                 appDir = new File(cache1.getParent());
                Log.d(TAG,appDir.getAbsolutePath());

                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 *******************");
                        }
                    }
                }

            }






        } catch (Exception e) { e.printStackTrace();}
    }

    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();
    }

我已经从 getCacheDir、getExternalCacheDir 和 getDataDir 中删除了所有文件。但在运行此代码后,我仍然可以看到我的应用缓存大小仍然相同。我现在该怎么办 ?

我正在检查缓存的 PFB 图像

缓存图像

手动清除缓存和存储的PFB截图:

手动清除缓存

标签: androidcaching

解决方案


推荐阅读