7

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

public static void trimCache(Context myAppctx) {

    Context context = myAppctx.createPackageContext("com.thirdparty.game", 
            Context.CONTEXT_INCLUDE_CO|Context.CONTEXT_IGNORE_SECURITY);

    File cachDir = context.getCacheDir();        
    Log.v("Trim", "dir " + cachDir.getPath());

    if (cachDir!= null && cachDir.isDirectory()) {

        Log.v("Trim", "can read " + cachDir.canRead());
        String[] fileNames = cachDir.list();
        //Iterate for the fileName and delete
    }
}

My manifest has following permissions:

android.permission.CLEAR_APP_CACHE
android.permission.DELETE_CACHE_FILES

Now the problem is that the name of the cache directory is printed but the list of files cachDir.list() always returns null. I am not able to delete the cache directory since the file list is always null.

Is there any other way to clear the application cache?

Octavian Helm
  • 39,405
  • 19
  • 98
  • 102
Srao
  • 241
  • 2
  • 3
  • 5

4 Answers4

6

"android.permission.CLEAR_APP_CACHE" android.permission.DELETE_CACHE_FILES"

Ordinary SDK applications cannot hold the DELETE_CACHE_FILES permission. While you can hold CLEAR_APP_CACHE, there is nothing in the Android SDK that allows you to clear an app's cache.

Is there any other way to clear the application cache?

You are welcome to clear your own cache by deleting the files in that cache.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • given the correct permission, you could remove the cache folders of other apps in the external storage (only). it's not the same, but a lot of apps use those folders as the main place to put temporary files. – android developer Oct 02 '14 at 21:09
  • i want to know when ever user can click clear cache i can get notification or something else how to get?? – KOUSIK daniel Jul 03 '15 at 14:28
  • @KOUSIKdaniel: I *think* that your process will be terminated before the cache is cleared, but I am not certain of that. I do not know of any other notification that you would get. – CommonsWare Jul 03 '15 at 14:53
  • @CommonsWare Thank You if you are getting Information kindly share it. – KOUSIK daniel Jul 03 '15 at 14:57
  • @CommonsWare The Exact Question is i want when ever user press and clean cache from recent apps button i can get notification – KOUSIK daniel Jul 04 '15 at 05:51
2

Check out android.content.pm.PackageManager.clearApplicationUserData: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3.3_r1/android/content/pm/PackageManager.java/ The other hidden methods in that class might be useful, too.

In case you've never used hidden methods before, you can access hidden methods using Java reflection.

tigeroctopus
  • 103
  • 1
  • 4
1

poate iti merge asta

static int clearCacheFolder(final File dir, final int numDays) {

        int deletedFiles = 0;
        if (dir!= null && dir.isDirectory()) {
            try {
                for (File child:dir.listFiles()) {

                    //first delete subdirectories recursively
                    if (child.isDirectory()) {
                        deletedFiles += clearCacheFolder(child, numDays);
                    }

                    //then delete the files and subdirectories in this dir
                    //only empty directories can be deleted, so subdirs have been done first
                    if (child.lastModified() < new Date().getTime() - numDays * DateUtils.DAY_IN_MILLIS) {
                        if (child.delete()) {
                            deletedFiles++;
                        }
                    }
                }
            }
            catch(Exception e) {
                Log.e("ATTENTION!", String.format("Failed to clean the cache, error %s", e.getMessage()));
            }
        }
        return deletedFiles;
    }

    public static void clearCache(final Context context, final int numDays) {
        Log.i("ADVL", String.format("Starting cache prune, deleting files older than %d days", numDays));
        int numDeletedFiles = clearCacheFolder(context.getCacheDir(), numDays);
        Log.i("ADVL", String.format("Cache pruning completed, %d files deleted", numDeletedFiles));
    }
OWADVL
  • 10,704
  • 7
  • 55
  • 67
  • 1
    It worked. I prefer: `long now = new Date().getTime();` before the loop instead of declaring a new `now` instance for each file. – Hamzeh Soboh Jun 23 '16 at 06:37
0

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.

datu-puti
  • 1,306
  • 14
  • 33