【转载来自http://blog.csdn.net/top_code/article/details/27378141

在使用WebView+HTML5打造Web App时,某些场景下需要同步一些用户的隐私数据,例如用户登录成功后我们需要在不同页面同步用户的登录状态信息。此时就用到了CookieSyncManager。

developer官方文档介绍如下:

The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.

大致意思是CookieSyncManager 用于在内存和持久化存储器(例如数据库)同步cookie,为了得到最好的性能,浏览器的cookie被保存在内存中,并且会有一个单独的线程定时来进行同步。

CookieSyncManager 的用法如下:

1、获取CookieSyncManager 对象

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. CookieSyncManager.createInstance(context);    

2、在Activity的onResume中调用startSync方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     protected void onResume() {  
  3.         CookieSyncManager.getInstance().startSync();  
  4.         super.onResume();  
  5.     }  

3、在Activity的onPause中调用stopSync方法

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     protected void onPause() {  
  3.         CookieSyncManager.getInstance().stopSync();  
  4.         super.onPause();  
  5.     }  

4、如果想立即进行同步而不是等待定时器触发,可使用如下代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. CookieSyncManager.getInstance().sync();   

developer官方文档介绍如下:

The sync interval is 5 minutes, so you will want to force syncs manually anyway, for instance in onPageFinished(WebView, String). Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.


完整代码如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. CookieSyncManager.createInstance(context);    
  2.         CookieManager cookieManager = CookieManager.getInstance();    
  3.         cookieManager.setAcceptCookie(true);    
  4.         cookieManager.removeSessionCookie();  
  5.         cookieManager.setCookie(hostname, cookies);   
  6.         CookieSyncManager.getInstance().sync();  //强制立即同步cookie  

注意:在调用CookieManager.setCookie(String url, String value)方法时,需要特别注意url为https的链接
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐