2012-01-09 117 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(); 
    }