Android Foursquare accessToken:如何从内部类获取accessToken?

时间:2011-07-05 00:13:48

标签: java android foursquare

如何从下面的匿名内部类中获取accessToken?当我尝试在类外部使用accessToken时,它显示为null。在我关闭内部类之后,我尝试使用accessToken显示一个toast,它只显示为null。我希望能够在asynctask中使用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);

            }
        }

1 个答案:

答案 0 :(得分:1)

     String accessToken = 
         url.substring(start + fragment.length(), url.length());

有您的访问令牌。

您可以将其传递给程序中的其他位置。您需要修改示例中给出的内部类以满足您的需要。截至目前,它只是在对话框中显示令牌。