Integrate Twitter Authentication In Android Application
Posted By : Keshav Gupta | 18-Jan-2018
Server Side Configuration:
1.Create a application at twitter developer account following on this link.
https://apps.twitter.com/
2.Get consumerkey and secretkey from there and save it locally as it will be needed in application side.
Android Application Code:
1.add twitter sdk with in android application.You need to add following dependencies and need to include jcenter() in app/build.gradle.Code will be like this
repositories {
jcenter()
}
dependencies {
compile 'com.twitter.sdk.android:twitter-core:3.1.1'
compile 'com.twitter.sdk.android:tweet-ui:3.1.1'
compile 'com.twitter.sdk.android:tweet-composer:3.1.1'
compile 'com.twitter.sdk.android:twitter-mopub:3.1.1'
}
2.Create a class named as AppConstants where we will put above generated credentials.Code will be like:
public class AppConstants {
// replace below credentials with your application
public static final String TWITTER_KEY = "XXXXXXXXXXXXXXXXXXXXXX";
public static final String TWITTER_SECRET = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static boolean isInternetIsAvailable(Context mContext) {
ConnectivityManager connectivity = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
3.Now create a Application class named as MainApplication and will initiate twitter configuration using consumerkey and secretkey.Make sure that its entry should be done in application tag.
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(AppConstants.TWITTER_KEY,AppConstants.TWITTER_SECRET))
.debug(true)
.build();
Twitter.initialize(config);
}
}
4.Now create a layout xml file named as activity_twitter which will host button to trigger twitter auth.File will be like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.twitterintegration.TwitterActivity">
<Button
android:id="@+id/connect_twitter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login With Twitter"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<com.twitter.sdk.android.core.identity.TwitterLoginButton
android:id="@+id/twitter_login_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:visibility="gone" />
</android.support.constraint.ConstraintLayout>
5.Now create TwitterActivity class where we will set callback for twitter and then trigger login and further we will collect user data using AccountService.Code for this class will be like.
package com.twitterintegration;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterCore;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import com.twitter.sdk.android.core.models.User;
import com.twitter.sdk.android.core.services.AccountService;
import retrofit2.Call;
public class TwitterActivity extends AppCompatActivity {
private Button twitterbtn;
private TwitterLoginButton twitterLoginButton;
private Context context;
private TwitterSession session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_twitter);
context=TwitterActivity.this;
twitterbtn=findViewById(R.id.connect_twitter);
twitterLoginButton=findViewById(R.id.twitter_login_btn);
twitterbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (AppConstants.isInternetIsAvailable(context)) {
makeloginwithTwitter();
} else {
Toast.makeText(context,"Oops connection suspended!enable internet connection", Toast.LENGTH_SHORT).show();
}
}
});
}
public void makeloginwithTwitter()
{
twitterLoginButton.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
session = result.data;
Log.e("Result", session.toString());
String msg = "@" + session.getUserName() + " logged in! (#" + session.getUserId() + ")";
Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
getUserData();
}
@Override
public void failure(TwitterException exception) {
Log.d("TwitterKit", "Login with Twitter failure", exception);
}
});
twitterLoginButton.performClick();
}
public void getUserData() {
TwitterCore twitterCore=TwitterCore.getInstance();
AccountService accountService=twitterCore.getApiClient(session).getAccountService();
Call<User> user=accountService.verifyCredentials(true,false,true);
user.enqueue(new Callback<User>() {
@Override
public void success(Result<User> userResult) {
User user = userResult.data;
String twitterImage = user.profileImageUrl;
try {
Log.e("imageurl", user.profileImageUrl);
Log.e("name", user.name);
Log.e("des", user.description);
Log.e("followers ", String.valueOf(user.followersCount));
Log.e("createdAt", user.createdAt);
Log.e("screenname", user.screenName);
Log.e("screenname", String.valueOf(user.getId()));
Log.e("twid", String.valueOf(user.getId()));
Log.e("twfname", user.name);
Log.e("twlname", user.name);
Log.e("twimage", user.profileImageUrl);
Toast.makeText(context,userResult.toString(),Toast.LENGTH_SHORT).show();
// put local server api call here to save user data
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(context,"Unable to login"+e.getMessage(),Toast.LENGTH_SHORT).show();
}
}
@Override
public void failure(TwitterException exception) {
Toast.makeText(context,"Unable to login"+exception.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
twitterLoginButton.onActivityResult(requestCode, resultCode, data);
}
}
6.That's all you have to do to serve twitter authentication in your application.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Keshav Gupta
Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.