Android之webview遇到的问题记录

问题一、cookie同步问题

有一个需求,在android中需要通过webview打开h5页面,并且需要把登录状态带到h5页面中,可以通过给webview要加载的url设置cookie的方式,同步登录状态。代码如下:

public void synCookies(Context context, String url) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.setCookie(url, cookies);//cookies是在HttpClient中获得的cookie
        String c = cookieManager.getCookie(url);
        Log.v(TAG,"=======cookies"+c);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

            CookieSyncManager.createInstance(getApplicationContext());
            CookieSyncManager.getInstance().sync();
        } else {
            cookieManager.flush();
        }
    }

这里当时遇到一个问题,看别人写的会在setCookie(url,cookies)之前调用cookieManager.removeSessionCookies()方法清除cookie。
这种情况下在android4.3的真机和模拟器上均会出现登录状态同步失败的问题。
去查看源码发现,cookieManager.removeSessionCookie();

 /**
     * Removes all session cookies, which are cookies without an expiration
     * date.
     * <p>
     * This method is asynchronous.
     * If a {@link ValueCallback} is provided,
     * {@link ValueCallback#onReceiveValue(T) onReceiveValue()} will be called on the current
     * thread's {@link android.os.Looper} once the operation is complete.
     * The value provided to the callback indicates whether any cookies were removed.
     * You can pass {@code null} as the callback if you don't need to know when the operation
     * completes or whether any cookie were removed, and in this case it is safe to call the
     * method from a thread without a Looper.
     * @param callback a callback which is executed when the session cookies have been removed
     */
    public abstract void removeSessionCookies(ValueCallback<Boolean> callback);

此方法会清除没有过期时间的cookie,(至于为什么没有同步成功,还没弄清楚)如果想清除cookie可以调用removeAllCookie(),这时就可以同步成功了。

另外也可以不调用此方法,因为调用setCookie()的时候,会把原来的相同的cookie替换掉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值