使用twitter4j android获取Twitter登录用户的Accestoken

时间:2014-03-10 08:25:45

标签: android twitter twitter4j

我可以使用android中的twitter4j成功登录Twitter。当我已经登录时,我想获得登录用户的accessstoken。见下面的代码。

Uri uri = getIntent().getData();

    if (uri != null && uri.toString().startsWith(TWITTER_CALLBACK_URL)) {

        String verifier = uri.getQueryParameter(TWITTER_OAUTH_VERIFIER);

        try {
            AccessToken accessToken = twitter.getOAuthAccessToken(requestToken, verifier);
            Editor e = mSharedPreferences.edit();

            e.putString(PREF_KEY_OAUTH_TOKEN, accessToken.getToken());
            e.putString(PREF_KEY_OAUTH_SECRET, accessToken.getTokenSecret());
            e.putBoolean(PREF_KEY_TWITTER_LOGIN, true);
            e.commit();

            FunctionToCall(accessToken);


        }
        catch (Exception e) {
        }
    }
    else{
        //HERE IS WHERE THE PROGRAM GOES WHEN THE USER IS ALREADY LOGGED IN.
        //I WANT TO GET THE ACCESS TOKEN HERE (AccessToken as object not as String)
        so that I can pass it to the function

        FunctionToCall(accessToken);        
    }
    loginToTwitter();
}

private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

        TwitterFactory factory = new TwitterFactory(configuration);
        twitter = factory.getInstance();
        try {
            requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
            TwitterLogin.this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    } else {
        //I want to get the ACCESS TOKEN OBJECT either here or at the above code
        //I can get the Access token as string (but I want AccessToken as object not as String)
        Log.e("Twitter OAuth Token", "> " + mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "0"));
    }
}

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:1)

使用SharedPreferences获取PreferenceManager即可获得Android上的偏好设置。

使用此代码获取设置并重新创建accessstoken:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(contextInTask);
String token = prefs.getString(PREF_KEY_OAUTH_TOKEN, "");
String secret = prefs.getString(PREF_KEY_OAUTH_SECRET, "");

AccessToken token = new AccessToken(token, secret);

如果你碰巧拥有(Twitter)userId,你也可以使用:

AccessToken token = new AccessToken(token, secret, userId);