【问题标题】:CookieSyncManager is now deprecated, what can I use instead?CookieSyncManager 现在已弃用,我可以使用什么来代替?
【发布时间】:2015-08-10 17:11:44
【问题描述】:

我在我的应用程序中使用了一个 cookie,它在所有浏览器中都可以正常工作,但是在 android 设备中,cookie 的设置速度没有我想要的那么快,保存 cookie 需要一些时间,当我删除曲奇饼。我能做些什么来让它更好地工作吗?提前感谢您的回答。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    webview = new WebView(this);
    webview.getSettings().setJavaScriptEnabled(true); // enable javascript

    CookieManager.setAcceptFileSchemeCookies(true);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.setAcceptCookie(true);
    cookieManager.acceptCookie();
    String cookie = CookieManager.getInstance().getCookie("mylink");

    final Activity activity = this;

    webview.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
        }
    });
    webview.loadUrl("mylink");

    setContentView(webview);
}

【问题讨论】:

    标签: android cookies webview synchronize


    【解决方案1】:

    在 Lollipop 及其他平台上,CookieManager 单例本身可以正常工作。 (参考链接 - http://developer.android.com/reference/android/webkit/CookieManager.html) 然而,在 Lollipop 之前,它还需要使用来自 CookieSyncManager 的附加静态方法。在 WebView 上设置 cookie 时,以下代码适用于所有 Android 版本 -

    CookieManager cookieManager = CookieManager.getInstance();
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        CookieSyncManager.createInstance(this);
    }
    cookieManager.setAcceptCookie(true);
    

    【讨论】:

    • 如果您告诉我如何在应用程序关闭时保存 cookie 以供重复使用(使 cookie 可用于整个应用程序),我将不胜感激?我正在 webview 上加载登录页面,每次如果应用程序关闭,我都必须重新登录!
    • 它不适合我..你能建议我更好的方法吗..
    【解决方案2】:

    只需启用 javascript 和 Dom 存储。这有助于我在我的 webview android 应用程序中记住我的登录详细信息。我没有使用任何 CookieManager,但启用它对我有用。

     webView.getSettings().setJavaScriptEnabled(true);
     webView.getSettings().setDomStorageEnabled(true);
    

    【讨论】:

    • 我尝试像任何其他解决方案一样启用 CookiesManager,但这个简单的解决方案效果很好!我想知道为什么..
    【解决方案3】:

    Nothing:“WebView 现在会根据需要自动同步 cookie。您不再需要创建或使用 CookieSyncManager。”

    正如 DarkKnight 所说,您可以测试您的应用目标是否低于 API 21 Lollipop (5.0),如果不是,则不再需要 CookieSyncManager。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-10
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 2019-10-01
      • 2020-01-18
      • 2012-04-10
      相关资源
      最近更新 更多