3

I want to clear my application cache programatically in Android Marshmallow 6.0. I tried the following code, but it's not working in Marshmallow.I read on stack overflow that below code is deprecated from API level 19. I add CLEAR_APP_CACHE permission in my Manifests.xml

 public  void trimCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

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

        // The directory is now empty so delete it
        return dir.delete();
    }
  • How is it not working? Did your app crashed? Please elaborate on it so people may help you better. – Hadi Satrio Oct 12 '16 at 05:29
  • @HadiSatrio Thanks for reply. I have seen in Monitors tab in Android studio. It doesn't free memory. And It also crash my application with the error of out of memory bound. I don't have memory card and i have only 500mb free memory in my phone. – shailesh pateliya Oct 12 '16 at 05:38
  • I am facing the same problem. If somebody has resolved please help. Thanks – Anjali Patel Jan 13 '18 at 05:29

1 Answers1

0

Add the following permission in your manifest:

<uses-permission android:name="android.permission.CLEAR_APP_CACHE" />

You should check for the external cache directory also.

public  void trimCache(Context context) {
        try {
            File dir = context.getCacheDir();
            if (dir != null && dir.isDirectory()) {
                deleteDir(dir);
            }
            File exDir = context.getExternalCacheDir();
            if (exDir != null && exDir.isDirectory()) {
                deleteDir(exDir);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
Tanay Mondal
  • 147
  • 2
  • 9