通过下面的代码,我已经能够保存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://");
}
}
最佳答案
您必须告诉CookieSyncManager在加载有问题的页面后进行同步。在您的示例代码中,onCreate
方法在WebView
尝试加载页面之前完全执行,因此同步过程(异步发生)可能会在加载页面之前完成。
相反,告诉CookieSyncManager同步WebViewClient中的onPageFinished。那应该给您您想要的。
CookieSyncManager Documentation是如何正确执行此操作的不错的阅读方法。
您可以通过以下方法设置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将此同步到其他位置。我还没有测试过,所以让我知道它是否有效。