Clearing Android Cache

Hi, I have an application with a code size of about 1/2 MB. The app includes web browsing to display multiple pages. Therefore, my cache ends at 2.5 MB. Not much, but enough. How can I clear the onDestroy cache?

thanks!

+2
source share
2 answers

put this code in onDestroy () for a clean application cache

@Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            trimCache(this);
           // Toast.makeText(this,"onDestroy " ,Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

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

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

        // The directory is now empty so delete it
        return dir.delete();
     }
+8
source

As indicated in the link above, you can get the cache directory and then delete it along with your children to clear the cache as follows:

    File dir = context.getCacheDir(); 
    if (dir != null && dir.isDirectory()) { 
     deleteDir(dir); 
    } 


    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(); 
   }
+2
source

All Articles