Android开发的新手我正在尝试应用此处描述的Web身份验证方法:https://sites.google.com/site/oauthgoog/oauth-practices/mobile-apps-for-complex-login-systems/samplecode
以下是结果代码:
public class LoginActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_PROGRESS);
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient() {
// Show loading progress in activity's title bar.
@Override
public void onProgressChanged(WebView view, int progress) {
setProgress(progress * 100);
}
});
webview.setWebViewClient(new WebViewClient() {
// When start to load page, show url in activity's title bar
@Override
public void onPageStarted(WebView view, String url,
Bitmap favicon) {
setTitle(url);
}
@Override
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
// Get the cookie from cookie jar.
String cookie = CookieManager.getInstance().getCookie(url);
if (cookie == null) {
return;
}
// Cookie is a string like NAME=VALUE [; NAME=VALUE]
String[] pairs = cookie.split(";");
for (int i = 0; i < pairs.length; ++i) {
String[] parts = pairs[i].split("=", 2);
// If token is found, return it to the calling activity.
parts[0] = parts[0].trim();
if (parts.length == 2 && parts[0].equalsIgnoreCase("MY_PRIVATE_TOKEN")) {
Intent result = new Intent();
result.putExtra("token", parts[1]);
setResult(RESULT_OK, result);
finish();
}
}
}
});
String queryStringAndroidId = "?aid="+Secure.getString(this.getContentResolver(),Secure.ANDROID_ID);
setContentView(webview);
String urlToLoginPage =getString(R.string.web_login_page).concat(queryStringAndroidId);
webview.loadUrl(urlToLoginPage);
}
}
我的问题在于 onPageFinished 方法。当第一次显示webview时,会调用此方法,这是我没想到的。如果身份验证cookie已存在,则会立即关闭活动。据我所知,这个方法应该只在webview中显示另一个页面时调用(除了我调用的第一个页面之外),我错了吗?有人可以对这种行为有所了解吗?非常感谢。
顺便说一句,我看到了这个解决方案:onPageFinished not firing correctly when rendering web page但我不喜欢这样的复飞。我宁愿理解为什么在我不期望它时触发方法。感谢。