我有一個活動,通過在webview中顯示重定向url後攔截重定向url來執行OAuth身份驗證。然而,onPageFinished函數由於某種原因以某種方式被調用了兩次,這真的弄亂了我的應用程序。以下是代碼:Android Webview 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...}
P.S. 請不要將此標記爲重複項...我已閱讀StackOverflow上的類似問題,並調用ShouldOverrideUrlLoading對我不起作用(這就是爲什麼我首先使用onPageFinished())。
這不是我的情況 –
這完全沒有工作 –