[英]How to store cookies in an Android WebView?
Currently I'm trying to store cookies in my android app. 目前,我正在尝试将Cookie存储在我的android应用中。 My app is loading a web page using the android webview.
我的应用正在使用android webview加载网页。 The activity is below.
该活动如下。
But, I need help to store cookies in my app. 但是,我需要帮助将Cookie存储在我的应用程序中。 The web page I'm loading is creating the cookies with php using the
setcookie()
function. 我正在加载的网页正在使用
setcookie()
函数通过php创建cookie。 It works fine in a regular browser, but I'm a beginner app developer and it doesn't work in my android WebView. 它在常规浏览器中可以正常工作,但是我是新手应用开发人员,因此在我的Android WebView中不起作用。
I need your help to store the cookie with php (on the loaded web page). 我需要您的帮助,以使用php存储Cookie(在已加载的网页上)。
PS I want the cookie to last forever (if possible). 附言:我希望cookie能够永远持续下去(如果可能的话)。
package com.stuff;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
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);
// 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();
}
});
//This will load the webpage that we want to see
webview.loadUrl("http://www.need-cookies.com/");
}
}
Take a look at the CookieSyncManager class, basically you can do this: 看一下CookieSyncManager类,基本上可以做到这一点:
CookieSyncManager syncManager = CookieSyncManager.createInstance(webView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setCookie(); // Here your cookie
syncManager.sync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.