0

如何从下面的匿名内部类中获取 accessToken?当我尝试在类外使用 accessToken 时,它显示为空。在我关闭内部类后,我试图用 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);

            }
        }
4

1 回答 1

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

有你的访问令牌。

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

于 2011-07-05T00:19:13.673 回答