Android WebView js混合cookie和localStorage存储

一、cookie存储和取出:

     (1)存储:     

     -------------------
     **在loadURL之前调用**
     --------------------

    /**
     * 同步一下cookie
     */
    public void synCookies(String url) {
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        cookieManager.acceptCookie();
        cookieManager.removeSessionCookie();// 移除
        cookieManager.removeAllCookie();
        /**
         * cookies是在HttpClient中获得的cookie
         */
        String token = (String) SpUtils.getParam(getApplicationContext(), Constant.TOKEN, "'");
        String phone = (String) SpUtils.getParam(getApplicationContext(), Constant.PHONENUMBER, "'");
        if (TextUtils.isEmpty(token)) {
            return;
        }
        cookieManager.setCookie(url, Constant.UICPS_USERID + "=" + token);
        cookieManager.setCookie(url, Constant.UICPS_USERPHONE + "=" + phone);
        /**
         *  判断系统当前版本,同步方式不一样
         */
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.flush();
        } else {
            CookieSyncManager.createInstance(getApplicationContext()).sync();
        }
    }

   

    (2)取出:

       url:web地址
if (CookieManager.getInstance().hasCookies()) {//如果存在token就获取 String cookies = CookieManager.getInstance().getCookie(url); }

二、LocalStorage存储和取出:  设置LocalStorage 在onPageFinished中调用

     (1)存储   

         第一步:设置 

 //存储设置
webSettings.setDomStorageEnabled(true); webSettings.setAppCacheMaxSize(1024 * 1024 * 8); String appCachePath = getContext().getCacheDir().getAbsolutePath(); webSettings.setAppCachePath(appCachePath);

        第二步:存储


    /**
     * 网页加载完毕
     */
    @Override
    protected void onPageFinished(WebView view, String url) {
        writeLocalStorage();
    }

    /**
     * 写入LocalStorage
     */
    private void writeLocalStorage() {
        String token = (String) SpUtils.getParam(getApplicationContext(), Constant.TOKEN, "");
        String phone = (String) SpUtils.getParam(getApplicationContext(), Constant.PHONENUMBER, "");
        if (TextUtils.isEmpty(token)) {
            return;
        }
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            if (contentWebView != null) {
                contentWebView.evaluateJavascript("window.localStorage.setItem('" + Constant.UICPS_USERID + "','" + token + "');", null);
                contentWebView.evaluateJavascript("window.localStorage.setItem('" + Constant.UICPS_USERPHONE + "','" + phone + "');", null);
            }
        } else {
            if (contentWebView != null) {
                contentWebView.loadUrl("javascript:localStorage.setItem('" + Constant.UICPS_USERID + "','" + token + "');");
                contentWebView.loadUrl("javascript:localStorage.setItem('" + Constant.UICPS_USERPHONE + "','" + phone + "');");
            }
        }
    }

       

      (2)取出

             在前端取出

             

 //token为存入的key值
localStorage.getItem("token")

       web 参考API:

       https://blog.csdn.net/CodingEnding/article/details/78898210

    

三、常用属性

         mWebView.getSettings().setJavaScriptEnabled(true);
        //设置渲染效果优先级,高
        mWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        //设置缓存模式
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
        String cacheDirPath = APP_CACAHE_DIRNAME;
        //设置数据库缓存路径
        mWebView.getSettings().setDatabasePath(cacheDirPath);
        //设置 应用 缓存目录
        mWebView.getSettings().setAppCachePath(cacheDirPath);
        //开启 DOM 存储功能
        mWebView.getSettings().setDomStorageEnabled(true);
        //开启 数据库 存储功能
        mWebView.getSettings().setDatabaseEnabled(true);
        //开启 应用缓存 功能
        mWebView.getSettings().setAppCacheEnabled(true);
 
webSettings.setBlockNetworkImage(false);//该方法的作用是是否屏蔽图片的加载。可以利用这个方法来实现图片的延迟加载:在onPageStarted时屏蔽图片加载,在onPageFinished时开启图片加载。
//设置是否阻止加载网络资源(不仅仅是图片),默认是`false`,如果设置为`true`,那么网络上的js,css,图片等资源都不会加载
WebSettings.setBlockNetworkLoads(false);
//设置渲染线程的优先级
//该方法在 Api 18之后被废弃,优先级由WebView自己管理
//不过任然建议将其设置为 HIGH,来提高页面渲染速度
WebSettings.setRenderPriority(RenderPriority.HIGH);
/**
     * 清除WebView缓存
     */
    public void clearWebViewCache() {
        /**清理Webview缓存数据库,缓存文件由程序自动生成
         * /data/data/package_name/database/webview.db
         * /data/data/package_name/database/webviewCache.db
         **/
        try {
            //因为他们都是文件,所以可以用io方式删除,具体方法可以自己写
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //WebView 缓存文件
        File webviewCacheDir = new File(APP_CACAHE_DIRNAME);
        //删除webview 缓存目录
        if (webviewCacheDir.exists()) {
            //具体的方法自己写
            deleteFile(webviewCacheDir);
        }
    }
LOAD_CACHE_ONLY:  不使用网络,只读取本地缓存数据

LOAD_DEFAULT:  根据cache-control决定是否从网络上取数据。

LOAD_CACHE_NORMAL: API level 17中已经废弃, 从API level 11开始作用同LOAD_DEFAULT模式

LOAD_NO_CACHE: 不使用缓存,只从网络获取数据.

LOAD_CACHE_ELSE_NETWORK,只要本地有,无论是否过期,或者no-cache,都使用缓存中的数据。
 
原文地址:https://www.cnblogs.com/huihuizhang/p/11766519.html