Get a User's email address from Twitter (Android)

前端 未结 5 1459
悲&欢浪女
悲&欢浪女 2021-01-21 06:49

How can i get email address of a user via twitter API? I\'m using Twitter4j for Sign in with twitter

5条回答
  •  萌比男神i
    2021-01-21 07:04

    first of all make sure you activated Request email addresses from users in your twitter app Permissions section


    then follow Twitter Documentation steps:

    1. Installation process: which simply imports the sdk package of twitter

    and i'm using only the core package

    compile 'com.twitter.sdk.android:twitter-core:3.1.1'
    

    Initialize Twitter Kit on your Activity onCreate method

    Twitter.initialize(this);
    

    Add your App id and secret to strings.xml file

    XXXXXXXXXXX
    XXXXXXXXXXX
    

    2. Add the Button:

    
    
    HINT: you can use a custom button just follow this simple answer
    private TwitterLoginButton twitterBtn;
    

    ...

    twitterBtn = (TwitterLoginButton) findViewById(R.id.twitter_connect);
    twitterBtn.setCallback(new Callback() {
        @Override
        public void success(Result result) {
            // Do something with result, which provides a TwitterSession for making API calls
            // which is do the callback from twitter to get the Email
            TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
            TwitterAuthToken authToken = session.getAuthToken();
            String token = authToken.token;
            String secret = authToken.secret;
    
            TwitterAuthClient authClient = new TwitterAuthClient();
            authClient.requestEmail(session, new Callback() {
                @Override
                public void success(Result result) {
                    // Do something with the result, which provides the email address
                    // the email is saved in the result variable 'result.data'
                    Toast.makeText(getBaseContext(), "Email" + result.data, Toast.LENGTH_LONG).show();
                }
    
                @Override
                public void failure(TwitterException exception) {
                    // Do something on failure
                }
            });
        }
    
        @Override
        public void failure(TwitterException exception) {
            // Do something on failure
        }
    });
    

    Next, pass the result of the authentication Activity back to the button:

    // Pass the activity result to the login button.
    twitterBtn.onActivityResult(requestCode, resultCode, data);
    

    like so:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        // Pass the activity result to the login button.
        twitterBtn.onActivityResult(requestCode, resultCode, data);
    }
    

提交回复
热议问题