android webview 获取cookie,Android WebView 之Cookie

!.同步 cookie 要在 WebView 加载 url 之前,否则 WebView 无法获得相应的 cookie,也就无法通过验证。

2.cookie应该被及时更新,否则很可能导致WebView拿的是旧的session id和服务器进行通信。

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)

{

// 清除结果

}

});

避免WebView内存泄露的一些方式

1.以将 Webview 的 Activity 新起一个进程,结束的时候直接System.exit(0);退出当前进程;

启动新进程,主要代码:  AndroidManifest.xml 配置文件代码如下

android:name=".ui.activity.WebActivity"

android:process=":lyl.boon.process.web">

在新进程中启动 Activity ,里面传了 一个 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内容,然后移除 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();

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值