How can I clear the Android app cache?

前端 未结 4 1027
青春惊慌失措
青春惊慌失措 2020-12-03 06:04

I am writing a app which can programatically clear application cache of all the third party apps installed on the device. Following is the code snippet for Android 2.2

4条回答
  •  庸人自扰
    2020-12-03 06:45

    I'm not sure how appropriate this is in terms of convention, but this works so far for me in my Global Application class:

        File[] files = cacheDir.listFiles();
        for (File file : files){
            file.delete();
        }
    

    Of course, this doesn't address nested directories, which might be done with a recursive function like this (not tested extensively with subdirectories):

    deleteFiles(cacheDir);
    
    private void deleteFiles(File dir){
        if (dir != null){
            if (dir.listFiles() != null && dir.listFiles().length > 0){
                // RECURSIVELY DELETE FILES IN DIRECTORY
                for (File file : dir.listFiles()){
                    deleteFiles(file);
                }
            } else {
                // JUST DELETE FILE
                dir.delete();
            }
        }
    }
    

    I didn't use File.isDirectory because it was unreliable in my testing.

提交回复
热议问题