!.同步 cookie 要在 WebView 加載 url 之前拴泌,否則 WebView 無法獲得相應(yīng)的 cookie咏尝,也就無法通過驗證。
2.cookie應(yīng)該被及時更新格仲,否則很可能導(dǎo)致WebView拿的是舊的session id和服務(wù)器進行通信搁廓。
cookie -------實例化
if(android.os.Build.VERSION.SDK_INT<21){
? CookieSyncManager.createInstance(context);
}
?CookieManager?cookieManager?=?CookieManager.getInstance();
cookie-----------更新姿勢
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
cookieManager.flush();
} else {
CookieSyncManager.createInstance(this.getApplicationContext());
CookieSyncManager.getInstance().sync();
}
cookie 獲纫薄(指定url)
private String getCookie(String url){
CookieManager cookieManager =CookieManager.getInstance();
return cookieManager.getCookie(url);
}
cookie 清除
CookieManager.getInstance().removeAllCookies(new?ValueCallback()?{
????????@Override
publicvoidonReceiveValue(Booleanvalue)
{
????????????//?清除結(jié)果
????????}
????});
避免WebView內(nèi)存泄露的一些方式
1.以將 Webview 的 Activity 新起一個進程,結(jié)束的時候直接System.exit(0);退出當前進程境蜕;
啟動新進程蝙场,主要代碼: ?AndroidManifest.xml 配置文件代碼如下
android:name=".ui.activity.WebActivity"
android:process=":lyl.boon.process.web">
在新進程中啟動 Activity ,里面?zhèn)髁?一個 Url:
Intent?intent?=newIntent("com.ui.activity.WebActivity");
Bundle?bundle?=newBundle();
bundle.putString("url",?gankDataEntity.getUrl());
intent.putExtra("bundle",bundle);
startActivity(intent);
然后在WebActivity的onDestory() 最后加上 System.exit(0); 殺死當前進程粱年。
2.在 Activity 銷毀的時候售滤,可以先讓 WebView 加載null內(nèi)容,然后移除 WebView台诗,再銷毀 WebView完箩,最后置空。
代碼如下:
@Override
protectedvoidonDestroy(){
if(mWebView?!=null)?{
mWebView.loadDataWithBaseURL(null,"","text/html","utf-8",null);
mWebView.clearHistory();
((ViewGroup)?mWebView.getParent()).removeView(mWebView);
mWebView.destroy();
mWebView?=null;
}
super.onDestroy();
}