Twitter Login for Android app

2019-07-20 08:27发布

can any one tell me the proper steps to perform the Open Auth for twitter login from my Android app? and one more thing is it posible to perform the login authentication of the twitter account without gng to the Twitter Login Page from my APP?

Idea is using the twitter account for loging in to my android APP (Authentication) ?

i hav tried it but it is gng to the twitter webview for the authentication without typing the username and password in my app?

so pls help me ! thanks in advance !!

3条回答
Juvenile、少年°
2楼-- · 2019-07-20 08:49

App Setup

Create App here https://developer.twitter.com/en/apps/create

Add Callback URLs to twittersdk:// (For Android SDK)

From App Details goto Keys and tokens and add in res/values/strings.xml

<string name="twitter_api_key">REPLACE_KEY</string>
<string name="twitter_api_secret">REPLACE_SECRET</string>

From App Details goto Permissions -> Edit

Access permission -> Read, write, and Direct Messages
Additional permissions -> Check to true (Request email address from users)
Save

Add INTERNET permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

Add twitter SDK dependency to build.gradle (Module:app)

dependencies {
    implementation 'com.twitter.sdk.android:twitter:3.1.1'
    //implementation 'com.twitter.sdk.android:twitter-core:3.1.1'
    //implementation 'com.twitter.sdk.android:tweet-ui:3.1.1'
}

In Activity

private TwitterAuthClient twitterAuthClient;

Custom Button Click

TwitterConfig config = new TwitterConfig.Builder(this)
    .logger(new DefaultLogger(Log.DEBUG))
    .twitterAuthConfig(new TwitterAuthConfig(getResources().getString(R.string.twitter_api_key), getResources().getString(R.string.twitter_api_secret)))
    .debug(true)
    .build();
Twitter.initialize(config);

twitterAuthClient = new TwitterAuthClient();

TwitterSession twitterSession = TwitterCore.getInstance().getSessionManager().getActiveSession();

if (twitterSession == null) {
    twitterAuthClient.authorize(this, new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            TwitterSession twitterSession = result.data;
            getTwitterData(twitterSession);
        }

        @Override
        public void failure(TwitterException e) {
            Log.e("Twitter", "Failed to authenticate user " + e.getMessage());
        }
    });
} else {
    getTwitterData(twitterSession);
}

private void getTwitterData(final TwitterSession twitterSession) {
    TwitterApiClient twitterApiClient = new TwitterApiClient(twitterSession);
    final Call<User> getUserCall = twitterApiClient.getAccountService().verifyCredentials(true, false, true);
    getUserCall.enqueue(new Callback<User>() {
        @Override
        public void success(Result<User> result) {

            String socialId = "", firstName = "", lastName = "", gender = "", birthday = "", email = "", picture = "";

            User user = result.data;
            socialId = user.idStr;
            email = user.email;
            /*picture = user.profileImageUrlHttps.replace("_normal", "");
            firstName = user.name;
            lastName = user.screenName;*/

            try {
                firstName = user.name.split(" ")[0];
                lastName = user.name.split(" ")[1];
            } catch (Exception e) {
                firstName = user.name;
                lastName = "";
            }

            Log.e("Twitter", "SocialId: " + socialId + "\tFirstName: " + firstName + "\tLastName: " + lastName + "\tEmail: " + email);
        }

        @Override
        public void failure(TwitterException exception) {
            Log.e("Twitter", "Failed to get user data " + exception.getMessage());
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (twitterAuthClient != null) {
        twitterAuthClient.onActivityResult(requestCode, resultCode, data);
    }
}
查看更多
smile是对你的礼貌
3楼-- · 2019-07-20 08:56

You will have to use the Twitter OAuth for the purpose of Authentication for your App.
The Example of twitter OAuth is described here

查看更多
女痞
4楼-- · 2019-07-20 09:04

It helps me for Twitter integration in android application.

This is offical Twitter Kit for Android(Twitter SDK)

check this link https://dev.twitter.com/twitterkit/android/installation

dependencies {
// Include all the Twitter APIs
compile 'com.twitter.sdk.android:twitter:3.0.0'
// (Optional) Monetize using mopub
compile 'com.twitter.sdk.android:twitter-mopub:3.0.0'
}

repositories {
  jcenter()
 }

public class CustomApplication {
  public void onCreate() {
   TwitterConfig config = new TwitterConfig.Builder(this)
       .logger(new DefaultLogger(Log.DEBUG))
       .twitterAuthConfig(new TwitterAuthConfig("CONSUMER_KEY",   "CONSUMER_SECRET"))
    .debug(true)
 .build();
Twitter.initialize(config);
}
}

Inside your layout, add a Login button with the following code:

<com.twitter.sdk.android.core.identity.TwitterLoginButton
 android:id="@+id/login_button"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content" />

In the Activity

loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
loginButton.setCallback(new Callback<TwitterSession>() {
 @Override
 public void success(Result<TwitterSession> result) {
    // Do something with result, which provides a TwitterSession for making API calls
 }

 @Override
 public void failure(TwitterException exception) {
     // Do something on failure
  }
 });

@Override
protected void onActivityResult(int requestCode, int resultCode,   Intent data) {
  super.onActivityResult(requestCode, resultCode, data);

  // Pass the activity result to the login button.
  loginButton.onActivityResult(requestCode, resultCode, data);
}
查看更多
登录 后发表回答