美文网首页
Android WebView 之Cookie

Android WebView 之Cookie

作者: 舒童1024 | 来源:发表于2018-07-30 15:15 被阅读130次

!.同步 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();

}

相关文章

网友评论

      本文标题:Android WebView 之Cookie

      本文链接:https://www.haomeiwen.com/subject/gojfvftx.html