如何在Android网络视图中永久保存cookie?

2022-09-01 22:00:07

通过下面的代码,我已经能够保存一个cookie,但是一旦我关闭应用程序,Cookie就会消失。

这是如何引起的,我该如何解决?

package com.jkjljkj

import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class Activity extends Activity {

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        CookieSyncManager.createInstance(getBaseContext());

        // Let's display the progress in the activity title bar, like the
        // browser app does.


        getWindow().requestFeature(Window.FEATURE_PROGRESS);

        WebView webview = new WebView(this);
        setContentView(webview);


        webview.getSettings().setJavaScriptEnabled(true);

        final Activity activity = this;
        webview.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
             // Activities and WebViews measure progress with different scales.
             // The progress meter will automatically disappear when we reach 100%
             activity.setProgress(progress * 1000);
        }
      });

      webview.setWebViewClient(new WebViewClient() {

         public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
              //Users will be notified in case there's an error (i.e. no internet connection)
              Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
         }
      });

      CookieSyncManager.getInstance().startSync();
      CookieSyncManager.getInstance().sync();

     //This will load the webpage that we want to see
      webview.loadUrl("http://");

   }
}

答案 1

您必须告诉CookieSyncManager在加载相关页面进行同步。在示例代码中,该方法在尝试加载页面之前完全执行,因此同步过程(异步发生)可能会在加载页面之前完成。onCreateWebView

相反,告诉 CookieSyncManager 在 WebViewClient 中同步 onPageFinished。这应该能给你带来你想要的。

CookieSyncManager 文档是有关如何正确执行此操作的好读物。

以下是如何设置 WebViewClient 实现以为您执行此操作:

webview.setWebViewClient(new WebViewClient() {
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        //Users will be notified in case there's an error (i.e. no internet connection)
        Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
    }

    public void onPageFinished(WebView view, String url) {
        CookieSyncManager.getInstance().sync();
    }
);

您不需要告诉CookieSyncManager在其他地方同步。我还没有测试过,所以让我知道它是否有效。


答案 2

.sync() 是强制立即同步,并且必须在页面加载后调用,因为它与缓存同步 RAM,因此 cookie 在调用之前必须位于 ram 中。

如果您使用此方案,系统每5分钟自动同步一次

onCreate: 
CookieSyncManager.createInstance(context)

onResume:
CookieSyncManager.getInstance().startSync()

onPause:
CookieSyncManager.getInstance().stopSync()

我想你没有等待5分钟,所以系统保存饼干。


推荐