Android Twitter第三方登录&获取用户信息

Android接入Twitter先是去了Twitter的开发者网站,发现太麻烦,不太适用目前项目,转而接入了Twitter为java提供的twitter4j的jar包。
以下为接入Twitter4j的一些经验
官网地址:http://twitter4j.org/en/index.html#sourceCode 其中提供了jar包下载链接
Download 分为两个版本
・Latest stable version (稳定版)
・Latest snapshot build (快照版) 快照版应该是与时俱进版,即与下面的Source Code中提供的github网址的代码保持同步,大家根据自己的需求来选择下载(例如博主下载的就是快照版,因为需要获取到用户的Email,而这项信息在稳定版中是没有的。。。)
github: http://github.com/yusuke/twitter4j/

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;

public class TwitterLoginActivity extends Activity {
    // Constants
    static String TWITTER_CONSUMER_KEY = "Your consumer key";
    static String TWITTER_CONSUMER_SECRET = "Your consumer secret";
    // Preference Constants
    static String PREFERENCE_NAME = "twitter_oauth";
    static final String PREF_KEY_OAUTH_TOKEN = "oauth_token";
    static final String PREF_KEY_OAUTH_SECRET = "oauth_token_secret";
    static final String PREF_KEY_TWITTER_LOGIN = "isTwitterLogedIn";

    static final String TWITTER_CALLBACK_URL = "oauth://t4jsample";

    // Twitter oauth urls
    static final String URL_TWITTER_AUTH = "auth_url";
    static final String URL_TWITTER_OAUTH_VERIFIER = "oauth_verifier";
    static final String URL_TWITTER_OAUTH_TOKEN = "oauth_token";

    // Twitter
    private static Twitter twitter;
    private static RequestToken requestToken;
    private String verifier;
    private GameView gameView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        startLoginTwitter();
    }

    /** * 调用Twitter登录的地方调用此方法即可 */
    public void startLoginTwitter() {
        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();
        new Thread() {
            @Override
            public void run() {
                try {
                    requestToken = twitter
                            .getOAuthRequestToken(TWITTER_CALLBACK_URL);
                } catch (TwitterException e) {
                    e.printStackTrace();
                }

                TwitterLoginActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        if (null != requestToken.getAuthenticationURL()) {
                            gameView.loadUrl(requestToken.getAuthenticationURL());
                        }
                    }
                });

            }
        }.start();
    }

    public class GameWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            LogUtil.i("shouldOverrideUrlLoading:" + url);
            if (null != url) {
                Uri uri = Uri.parse(url);
                if ("oauth".equals(uri.getScheme())
                        && "t4jsample".equals(uri.getAuthority())) {
                    handleCallBack(uri);
                    return true;
                }
            };

            return false;
        }
    }

    private void handleCallBack(Uri uri) {
        // oAuth verifier
        verifier = uri.getQueryParameter(URL_TWITTER_OAUTH_VERIFIER);

        new Thread() {
            @Override
            public void run() {
                try {
                    // Get the access token
                    AccessToken accessToken = twitter.getOAuthAccessToken(
                            requestToken, verifier);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                                getUserInfo(accessToken);
                        }
                    }).start();
                } catch (Exception e) {
                    Log.e("Twitter Login Error", "> " + e.getMessage());
                }
            }
        }.start();
    }

    private void getUserInfo(AccessToken accessToken) {
        Gson gson = new GsonFactory().create();
        String userId = String.valueOf(accessToken.getUserId());
        try {
            User user = twitter.showUser(accessToken.getUserId());
            String userImage = user.getProfileImageURL().toString();
            String userName = user.getName();
            String userSrceenName = user.getScreenName();
            String userEmail = user.getEmail();
            Log.e("getTwitterInfo", "userId: " + userId + " userName : " + userName + " userImage : " + userImage + " userSrceenName : " + userSrceenName + " userEmail :" + userEmail);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, String> tw_resp = new HashMap<String, String>();
        tw_resp.put("userId", userId);
        tw_resp.put("userImage", userImage);
        tw_resp.put("userName", userName);
        tw_resp.put("userSrceenName", userSrceenName);
        tw_resp.put("userEmail", userEmail);
        String jsonString = gson.toJson(tw_resp);
    }
}

用户信息可以在Twitter4J jar包中的User类看,以下是可获取到的所有User相关信息

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package twitter4j;

import java.io.Serializable;
import java.util.Date;
import twitter4j.Status;
import twitter4j.TwitterResponse;
import twitter4j.URLEntity;

public interface User extends Comparable<User>, TwitterResponse, Serializable {
    long getId();

    String getName();

    String getEmail();

    String getScreenName();

    String getLocation();

    String getDescription();

    boolean isContributorsEnabled();

    String getProfileImageURL();

    String getBiggerProfileImageURL();

    String getMiniProfileImageURL();

    String getOriginalProfileImageURL();

    String getProfileImageURLHttps();

    String getBiggerProfileImageURLHttps();

    String getMiniProfileImageURLHttps();

    String getOriginalProfileImageURLHttps();

    boolean isDefaultProfileImage();

    String getURL();

    boolean isProtected();

    int getFollowersCount();

    Status getStatus();

    String getProfileBackgroundColor();

    String getProfileTextColor();

    String getProfileLinkColor();

    String getProfileSidebarFillColor();

    String getProfileSidebarBorderColor();

    boolean isProfileUseBackgroundImage();

    boolean isDefaultProfile();

    boolean isShowAllInlineMedia();

    int getFriendsCount();

    Date getCreatedAt();

    int getFavouritesCount();

    int getUtcOffset();

    String getTimeZone();

    String getProfileBackgroundImageURL();

    String getProfileBackgroundImageUrlHttps();

    String getProfileBannerURL();

    String getProfileBannerRetinaURL();

    String getProfileBannerIPadURL();

    String getProfileBannerIPadRetinaURL();

    String getProfileBannerMobileURL();

    String getProfileBannerMobileRetinaURL();

    boolean isProfileBackgroundTiled();

    String getLang();

    int getStatusesCount();

    boolean isGeoEnabled();

    boolean isVerified();

    boolean isTranslator();

    int getListedCount();

    boolean isFollowRequestSent();

    URLEntity[] getDescriptionURLEntities();

    URLEntity getURLEntity();

    String[] getWithheldInCountries();
}

你可能感兴趣的:(java,android,twitter)