2012-01-09 118 views
2

您好我已经得到了大约1/2MB的代码大小的应用程序。该应用程序包含一个显示多个页面的webview。因此我的缓存结束了2,5mb。不多,但足够。我怎样才能清除我的缓存onDestroy?清除机器人缓存

Thx!

+0

检查这个问题:http://stackoverflow.com/questions/2465432/android-webview-completely-clear-the-cache – 2012-01-09 11:02:27

+0

THX的链接。我认为这将帮助许多人,但不幸的是......我并没有真正得到它的保持。 :( 有没有办法来清除所有缓存的应用,不仅对的OnDestroy()中的WebView;事件 – 2012-01-09 19:49:04

回答

2

如上面提供的链接给,你可以得到的缓存目录,然后用其子删除它一起清除缓存如下:

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

那么对不起不是说这B4,但谢谢你帮 起初,我没有!见的只是清理mWebView点,但有点测试后,我意识到,mWebView是缓存源,而现在它的所有的工作就像一个魅力,我真的只是包括mWebView.ClearCache();(认为这是正确的避风港? “T在我所有的使用的WebView活动的onStop事件检查这段代码与我的实际项目) – 2012-03-05 20:41:02

+0

回报dir.delete();可能会失败,如果dir是空,因此而是进入第一,如果再返回false。最后。 – slott 2015-01-23 10:12:22

8

把这个代码的onDestroy()为明确的应用缓存

@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(); 
    }