1. 程式人生 > >Android之webview遇到的問題記錄

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替換掉。