WebView的缓存设置

1.优先缓存

好了,这里你是不是想问:既然这些图片已经存在手机缓存里面了,为什么Webview不能再把它显示出来呢?

这里我们需要设置下:

WebSettings webSettings= webView.getSettings();

webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

//WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); 默认不使用缓存!

LOAD_CACHE_ELSE_NETWORK的意思是:

Use cache if content is there, even if expired (eg, history nav) If it is not in the cache, load from network. Use with setCacheMode(int).

如果内容已经存在cache 则使用cache,即使是过去的历史记录。如果cache中不存在,从网络中获取!

所以加上这句,不仅可以使用cache离线显示用户浏览过的内容,还可以在有网络的情况下优先调用缓存,为用户减少流量!~

我有些费解的是,这个设置在我看来是很有利于用户体验的 为什么google不把它设置成默认的呢? 还需要开发者手动打开。猜想可能是因为相同页面可能会更新的原因!

如果离线加载出现乱码 可参考: http://androidturing.iteye.com/blog/1280656

http://androiddada.iteye.com/

2.缓存管理:

(1)clearCacheFolder(Activity.getCacheDir(), System.currentTimeMillis());//删除此时之前的缓存.

    // clear the cache before time numDays    
    private int clearCacheFolder(File dir, long numDays) {     
    int deletedFiles = 0if (dir!= null && dir.isDirectory()) {     
    try {     
    for (File child:dir.listFiles()) {     
    if (child.isDirectory()) {     
    deletedFiles += clearCacheFolder(child, numDays);    
    }    

    if (child.lastModified() < numDays) {     
    if (child.delete()) {     
    deletedFiles++;    
    }    
    }    
    }    
    } catch(Exception e) {     
    e.printStackTrace();    
    }    
    }    
    return deletedFiles;     
    }    

(2) 退出应用前删除缓存的方法!

File file = CacheManager.getCacheFileBaseDir();    
  if (file != null && file.exists() && file.isDirectory()) { for (File item : file.listFiles()) { item.delete();    
  }    
  file.delete();    
  }    
  context.deleteDatabase("webview.db");    
  context.deleteDatabase("webviewCache.db"); 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值