Tuesday, November 23, 2010

Android WebView - Clear The Cache

I have been asked a couple of times how to clear the cache from a WebView on an Android application. I will briefly explain the approach I am currently using:

You need to implement two methods one to retrieve all the cache data and one to delete each directories we find  cache (technically you could do it in one method but I prefer two).

Method to delete cache file(s):


  public static boolean DeleteDirectories(File d) { 
   String[] children = d.list(); 
   for (int i = 0; i < children.length; i++) { 
   boolean success = DeleteDirectories(new File(d, children[i])); 
   if (!success) { 
    return false; 
   } 
   } 
    return d.delete(); //Delete empty directory
    


Method to retrieve all directories from cache to delete:

public static void DeleteCache(Context context) { 
     try { 
    File d = context.getCacheDir(); 
    if (d != null && d.isDirectory()) { 
    DeleteDirectories(d);  
   
     } catch (Exception e) { 
        // TODO: handle as you please 
    
     } 



I normally call these methods when the user abandons the application by overriding the onDestroy() method in my main activity.

Example:

  @Override 
    protected void onDestroy() { 
     super.onDestroy();  
   try { 
DeleteCache(this);  
   } catch (Exception e) { 
       // TODO: handle as you please
   } 
    }

No comments:

Post a Comment