1.基本使用
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//返回true时在webview中打开,false在浏览器中打开
view.loadUrl(url);
return true;
}
});
web.setWebChromeClient(new WebChromeClient(){
@Override
public void onProgressChanged(WebView view, int newProgress) {
//进度监听
LogUtil.e(TAG, "onProgressChanged: progress -> " + newProgress );
}
});
WebSettings webSettings =webView .getSettings();
//允许显示js
webSettings.setJavaScriptEnabled(true);
2.与js进行互相调用
//可能需要允许js显示
webView.addJavascriptInterface(this, "demo");
@JavascriptInterface
public void clickOnAndroid(String param) {
//这里写给js调用后执行方法体
// <button onClick="window.demo.clickOnAndroid('come from js')">点击调用Native代码并传递参数</button>
}
交互的native方法是执行在子线程的,如果有ui更新操作,需要切换到UI线程
3.重写返回键
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
4.添加Cookie
synCookies(this, url, getCookieValue());
/**
* 同步cookie
*
* @param context
* @param url
*/
public static void synCookies(Context context, String url, List<Cookie> cookies) {
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeSessionCookie();
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);
StringBuilder sb = null;
for (Cookie cookie : cookies) {
sb = new StringBuilder();
sb.append(String.format(cookie.name() + "=%s", cookie.value()));
sb.append(String.format(";domain=%s", cookie.domain()));
sb.append(String.format(";path=%s", cookie.path()));
sb.append(String.format(";expiresAt=%s", cookie.expiresAt()));
cookieManager.setCookie(url, sb.toString());
}
CookieSyncManager.getInstance().sync();
String cookie = cookieManager.getCookie(url);
Log.e(TAG, "synCookies: cookie:" + cookie);
}
/**
* 获得cookie信息(okhttp为例)
*
* @return
*/
private List<Cookie> getCookieValue() {
List<Cookie> allCookie = OkHttpUtils.getInstance().getCookieJar().getCookieStore().getAllCookie();
/*Cookie cookie = allCookie.get(1);
Log.e(TAG, "getCookieValue: name:" + cookie.name() + " value:" + cookie.value() +
" hashcode:" + cookie.hashCode() +
" hostOnly:" + cookie.hostOnly() +
" secure:" + cookie.secure() +
" persistent:" + cookie.persistent());*/
return allCookie;
}
5.加载进度条
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int newProgress) {
if (newProgress == 100) {
pbLoading.setVisibility(View.INVISIBLE);
} else {
if (View.INVISIBLE == pbLoading.getVisibility()) {
pbLoading.setVisibility(View.VISIBLE);
}
pbLoading.setProgress(newProgress);
}
super.onProgressChanged(view, newProgress);
}
});