我有一个活动通过在 Web 视图中显示后拦截重定向 URL 来进行 OAuth 身份验证。但是,由于某种原因,onPageFinished 函数被调用了两次,这真的弄乱了我的应用程序。这是代码:
public class WebViewActivity extends Activity {
private WebView gWebView;
final String REDIRECT_URI = "https://localhost:5000/receive_code";
final String CLIENT_ID = "can't post it here";
final String CLIENT_SECRET = "can't post it here";
final String SCOPE = "basic names genomes analyses";
Hashtable<String, String> riskPairs;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
gWebView = (WebView) findViewById(R.id.webView1);
gWebView.loadUrl("https://api.23andme.com/authorize/?redirect_uri="
+ REDIRECT_URI + "&response_type=code&client_id=" + CLIENT_ID
+ "&scope=" + SCOPE);
Log.d("WEBVIEW", "got to webpage");
gWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (url.startsWith(REDIRECT_URI)) {
Log.d("WEBVIEW", "onpagefinished is called");
System.out.println("got to override");
if (url.indexOf("code=") != -1) {
//if the query contains code
String queryString = null;
try {
queryString = new URL(url).getQuery();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(queryString);
String[] params = queryString.split("&");
String code = null;
for (String param : params) {
if (param.startsWith("code=")) {
code = param.substring(param.indexOf('=') + 1);
}
}
gWebView.setVisibility(View.GONE);
new PostRequest().execute(code);
// don't go to redirectUri
}
}
}
});
}
class PostRequest extends AsyncTask<String,Void,String>{ code getting client data...}
PS请不要将此标记为重复...我在 StackOverflow 上阅读了一个类似的问题,并且调用 ShouldOverrideUrlLoading 对我不起作用(这就是我首先使用 onPageFinished() 的原因)。