以编程方式清除Android应用程序中的缓存


76

什么是以编程方式清除android应用程序中的缓存的正确方法。我已经在使用以下代码,但对我来说似乎不起作用

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

来自我的Android手机的图片


2
还要检查getExternalCacheDir()
Patrick Favre

@ for3st我们可以只为webview清除缓存吗?
Rizwan Ahmed

2
WebView.clearCache(boolean includeDiskFiles)将清除应用程序中所有Webvie的缓存
Patrick Favre


@RizwanAhmed您是否找到上述问题的解决方案
Vishwa Pratap

Answers:


143

如果您正在寻找自己的应用程序的删除缓存,则只需删除缓存目录,然后将其全部删除即可!

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

在该操作上要删除应用程序缓存的位置。也许可以在OnDestroy或应用程序中的某个位置执行此操作
dharam 2014年

1
此代码永远不会删除文件。当dir.isDirectory()== false时,它仅返回false。由于您无法删除非空目录,因此无法使用。您应该添加其他: if (dir != null && dir.isDirectory()) { ... } else if(dir.isFile()) { return dir.delete(); }
Pierfrancesco Soffritti 2015年

@dhams此方法是否也清除了我的共享首选项数据?因为我想保留它,只清除缓存中的图像!
萨蒂2015年

3
@Saty:不,这不能清除共享的偏好
Taifun

1
他们在文档中写道,我们不需要额外的权限即可执行此操作。“应用程序不需要额外的权限来读取或写入返回的路径,因为该路径位于其专用存储中。” developer.android.com/reference/android/content/...
YTerle

61

Kotlin有一个班轮

context.cacheDir.deleteRecursively()

8
完美的答案,这在Java中也应该可用:context.getCacheDir()。deleteRecursively()
JJ Du Plessis

15

dhams的答案是正确的(经过多次编辑后),但是正如代码的多次编辑所显示的那样,很难编写正确而健壮的代码来自己删除目录(带有子目录)。因此,我强烈建议您使用Apache Commons IO或其他可以帮助您实现此目的的API:

import org.apache.commons.io.FileUtils;

...

// Delete local cache dir (ignoring any errors):
FileUtils.deleteQuietly(context.getCacheDir());

PS:如果使用该目录,还请删除context.getExternalCacheDir()返回的目录。

为了能够使用Apache Commons IO,请将其添加到build.gradle文件中的以下dependencies部分:

compile 'commons-io:commons-io:2.4'

2
gradle文件中的编译行现在为implementation 'commons-io:commons-io:2.5'。我首先尝试了2.6,但是我遇到了一些错误,例如noSuchMethodException,所以现在请使用2.5版本。这里的最新版本:mvnrepository.com/artifact/commons-io/commons-io
Juan IgnacioAvendañoHuergo


2

我不确定,但是我也播了这段代码。这种鳕鱼的工作速度更快,在我看来,它也很简单。只需获取您的应用程序缓存目录并删除目录中的所有文件

public boolean clearCache() {
    try {

        // create an array object of File type for referencing of cache files   
        File[] files = getBaseContext().getCacheDir().listFiles();

        // use a for etch loop to delete files one by one
        for (File file : files) {

             /* you can use just [ file.delete() ] function of class File
              * or use if for being sure if file deleted
              * here if file dose not delete returns false and condition will
              * will be true and it ends operation of function by return 
              * false then we will find that all files are not delete
              */
             if (!file.delete()) {
                 return false;         // not success
             }
        }

        // if for loop completes and process not ended it returns true   
        return true;      // success of deleting files

    } catch (Exception e) {}

    // try stops deleting cache files
    return false;       // not success 
}

它通过getBaseContext()。getCacheDir()。listFiles()获取File数组中的所有缓存文件,然后通过file.delet()方法逐一删除。


不建议使用纯代码的答案,因为它们没有解释如何解决问题。请更新您的答案,以说明此问题已被其他接受和赞成的答案如何改善,并删除代码中无效文本的多个实例(“在此处输入代码”)。请查看我如何写一个好的答案
FluffyKitten

2

尝试这个

@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("EEEEEERRRRRROOOOOOORRRR", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null && dir.isDirectory()) {
        String[] children = dir.list();
        int i = 0;
        while (i < children.length) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
            i++;
        }
    }

    assert dir != null;
    return dir.delete();
}

如何使用您的代码并仅删除shared_prefs缓存?你能帮我吗……
Karan Israni

1

将这个代码onStop()的方法MainActivity

@Override
protected void onStop() {
    super.onStop();
    AppUtils.deleteCache(getApplicationContext());
}
public class AppUtils {
    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;
        }
    }
}

-1

此代码将删除应用程序的整个缓存,您可以检查应用程序设置并打开应用程序信息并检查缓存的大小。使用此代码后,您的缓存大小将为0KB。因此,享受干净的缓存。

 if (Build.VERSION_CODES.KITKAT <= Build.VERSION.SDK_INT) {
            ((ActivityManager) context.getSystemService(ACTIVITY_SERVICE))
                    .clearApplicationUserData();
            return;
        }

我认为这也清除了数据,而不仅仅是缓存。
hamza khan

这也将删除应用程序数据,而不仅仅是清除缓存。此clearApplicationUserData()api不应仅用于清除缓存。
Rajeev Jayaswal '20
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.