webView基本使用
原创
©著作权归作者所有:来自51CTO博客作者wx637304bacd051的原创作品,请联系作者获取转载授权,否则将追究法律责任
- 启用JavaScript
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
//settings.setAllowFileAccess(true);
//settings.setAllowFileAccessFromFileURLs(true);
//settings.setAllowContentAccess(true);
settings.setDatabaseEnabled(true);
settings.setDomStorageEnabled(true);
- 拦截加载过程中指定的url或者广告,重写
WebViewClient::shouldInterceptRequest
mWebView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(mRefreshLayout != null){
mRefreshLayout.finishRefresh();
}
}
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
Uri uri = request.getUrl();
//过滤基本的广告url和替换图片
if(uri.toString().equals("https://xxx.png")){
try {
InputStream localCopy = getAssets().open("empty.png");
return new WebResourceResponse("image/png", "UTF-8", localCopy);
}
catch (Exception e){
return new WebResourceResponse(null,null,null);
}
}
if (isAds(uri)){
return new WebResourceResponse(null,null,null);
}
return super.shouldInterceptRequest(view, request);
}
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
Log.i("tUrl", url);
}
});
其中Assert的目录和java,res同级
- 监控url加载进度,重写
WebChromeClient::onProgressChanged
mWebView.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
}
});
- 拦截href跳转,重写
WebViewClient::shouldOverrideUrlLoading
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString().equals("https://xxx")){
//取消当前链接
return true;
}
return super.shouldOverrideUrlLoading(view, request);
}