安卓WebView设置本地缓存和使用。

直接上源码吧,都有注解。

private void initWebView() { 
    //获取WebSetting对象
    final WebSettings settings = webView.getSettings();
    settings.setJavaScriptEnabled(true);//支持js脚本
    settings.setRenderPriority(WebSettings.RenderPriority.HIGH);//设置渲染优先级
    //隐藏缩放控件
    settings.setBuiltInZoomControls(false);
    settings.setDisplayZoomControls(false);
    //禁止缩放
    settings.setSupportZoom(false);
    //文件权限
    settings.setAllowFileAccess(true);
    settings.setAllowFileAccessFromFileURLs(true);
    settings.setAllowUniversalAccessFromFileURLs(true);
    settings.setAllowContentAccess(true);
    //缓存相关
    if(InternetUtil.checkInternet(context)){
        //有网络,则加载网络地址
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);//设置缓存模式LOAD_CACHE_ELSE_NETWORK
    }else{
        //无网络,则加载缓存路径
        settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }
    settings.setDomStorageEnabled(true);//开启DOM storage API功能
    settings.setDatabaseEnabled(true);//开启database storeage API功能
    String cacheDirPath = context.getFilesDir().getAbsolutePath()+ "/webcache";//缓存路径
    settings.setDatabasePath(cacheDirPath);//设置数据库缓存路径
    settings.setAppCachePath(cacheDirPath);//设置AppCaches缓存路径
    settings.setAppCacheEnabled(true);//开启AppCaches功能
}

清除缓存:

/** 
 * 清除WebView缓存 
 */  
public void clearWebViewCache(){  
	//清理Webview缓存数据库  
	try {  
		deleteDatabase("webview.db");   
		deleteDatabase("webviewCache.db");  
	} catch (Exception e) {  
		e.printStackTrace();  
	}  
	  
	//WebView 缓存文件  
	File appCacheDir = new File(getFilesDir().getAbsolutePath()+"/webcache");  
	Log.e(TAG, "appCacheDir path="+appCacheDir.getAbsolutePath());  
	  
	File webviewCacheDir = new File(getCacheDir().getAbsolutePath()+"/webviewCache");  
	Log.e(TAG, "webviewCacheDir path="+webviewCacheDir.getAbsolutePath());  
	  
	//删除webview 缓存目录  
	if(webviewCacheDir.exists()){  
		deleteFile(webviewCacheDir);  
	}  
	//删除webview 缓存 缓存目录  
	if(appCacheDir.exists()){  
		deleteFile(appCacheDir);  
	}  
}



  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值