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

时间:2014-05-28 09:47:43

标签: android

以编程方式清除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();
}

Image from my android phone

9 个答案:

答案 0 :(得分:97)

如果您正在寻找自己应用程序的删除缓存,那么只需删除缓存目录即可完成!

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

答案 1 :(得分:13)

科特琳有一个内衬

context.cacheDir.deleteRecursively()

答案 2 :(得分:11)

来自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'

答案 3 :(得分:4)

我认为您应该在clearApplicationData()

之前放置super.OnDestroy().

您的应用在关闭后无法处理任何方法。

答案 4 :(得分: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()获取File数组中的所有缓存文件.getCacheDir()。listFiles() 然后通过file.delet()方法

逐个删除

答案 5 :(得分:1)

尝试一下

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

答案 6 :(得分:1)

如果您使用的是 kotlin,则:

context.cacheDir.deleteRecursively()

答案 7 :(得分:0)

将此代码放入onStop()的{​​{1}}方法中

MainActivity
@Override
protected void onStop() {
    super.onStop();
    AppUtils.deleteCache(getApplicationContext());
}

答案 8 :(得分:-1)

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

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