android webview cookie 同步时有时候会出现同步不成功的问题解决

博客内容指出,Android中使用`cookieManager.removeSessionCookie()`可能会遇到同步问题,因为该方法是异步的,可能导致在同步新Cookie时被删除。解决方案是在调用`removeSessionCookie()`后使用`SystemClock.sleep(500)`确保删除操作完成再进行同步,从而避免同步失败。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这个问题不是随时重现,我们在同步之前会先删除所有之前的cookies,调用:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP /*&& method != null*/){cookieManager.removeSessionCookies(new ValueCallback() {@Overridepublic void onReceiveValue(Boolean value) {Log.d(TAG, "onReceiveValue value:"+value);}});}else{ cookieManager.removeSessionCookie();}

经过查阅n多stackoverflow后发现一个答案:You have used this line - if (sessionCookie != null) { cookieManager.removeSessionCookie(); }. To ensure you receive new cookie everytime.Seems like you have gone through same issue as I faced, check below link -removeSessionCookie() issue of android (code.google.com)it says that removeSessionCookie() is implemented in a thread, so whenever it is called; a thread starts and after your setCookie(url, cookieString); is called, it removes the new cookie you just set. So for some devices it works well as removeSessionCookie() is already executed, while, for some, it remove the cookie, and we get that problem.by using SystemClock.sleep(500); , you just gave system to finish removeSessionCookie() firstI suggest you remove this removeSessionCookie(); as you are setting only one cookie, so it won't conflict with other cookies. Your code will work seamlessly.

大概意思就是说, cookieManager.removeSessionCookie()这个方法是一个异步的方法,在删除还没有结束的时候,主线程调用CookieSyncManager.getInstance().sync();方法去同步,此时,removeSessionCookie()并没有删除结束,顺带就把刚刚同步过去的session给删除了,所以导致的同步失效,哎呀,发现问题,那么好解决了,在removeSessionCookie() 的时候SystemClock.sleep(500);ok!不会再出现烦人的同步失败重定向了。如果还有更好的方法希望给我留言,谢谢了!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值