0
如何从下面的匿名内部类获取accessToken?当我尝试在类的外部使用accessToken时,它显示为空。在关闭内部类之后,我试图显示一个带有accessToken的敬酒,它只显示为空。我希望能够在asynctask中使用accessToken来获取一些数据。我怎么能这样做呢?Android Foursquare accessToken:如何从内部类获取accessToken?
public class main extends Activity {
public static final String CALLBACK_URL = "url";
public static final String CLIENT_ID = "id";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String url =
"https://foursquare.com/oauth2/authenticate" +
"?client_id=" + CLIENT_ID +
"&response_type=token" +
"&redirect_uri=" + CALLBACK_URL;
// If authentication works, we'll get redirected to a url with a pattern like:
//
// http://YOUR_REGISTERED_REDIRECT_URI/#access_token=ACCESS_TOKEN
//
// We can override onPageStarted() in the web client and grab the token out.
WebView webview = (WebView)findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
String fragment = "#access_token=";
int start = url.indexOf(fragment);
if (start > -1) {
// You can use the accessToken for api calls now.
String accessToken = url.substring(start + fragment.length(), url.length());
Toast.makeText(main.this, "Token: " + accessToken, Toast.LENGTH_SHORT).show();
}
}
});
webview.loadUrl(url);
}
}
当我尝试使用类之外的accessToken时,它显示为空。在关闭内部类之后,我试图显示一个带有accessToken的敬酒,它只显示为空。 – mergesort
webview将异步加载。访问令牌在onCreate后不会立即可用。你必须建立一个方法'setAccessToken',内部类会在完成初始化完成时调用。任何其他需要令牌的代码都可以从那里开始。 – Thilo
它的工作!非常感谢。 – mergesort