<p>This post is about how to implement Twitter Integration in our Android app and let users do Sign In with a single click.</p> 
 
 
 
<div class="wp-block-buttons is-content-justification-center is-layout-flex wp-container-core-buttons-is-layout-a89b3969 wp-block-buttons-is-layout-flex"> 
<div class="wp-block-button"><a class="wp-block-button__link has-white-color has-text-color has-background" style="background-color: #020252;" href="https://github.com/arunk7839/TwitLoginExp"><strong>DOWNLOAD CODE</strong></a></div> 
</div> 
<div> </div> 
<p><amp-youtube layout="responsive" width="1200" height="675" data-videoid="FSK8zE10Uys" title="Android Twitter Integration Example"><a placeholder href="https://youtu.be/FSK8zE10Uys"><img src="https://i.ytimg.com/vi/FSK8zE10Uys/hqdefault.jpg" layout="fill" object-fit="cover" alt="Android Twitter Integration Example"></a></amp-youtube></p> 
<p>Integrating Twitter API in the Android app requires the app <span style="color: #008000;"><strong>Consumer Key (API Key)</strong> </span>and<span style="color: #008000;"> <strong>Consumer Secret (API Secret)</strong>.</span></p> 
<h4 class="h3"><span style="color: #000080;"><strong>Steps to generate Twitter API Key and API Secret</strong></span></h4> 
<p>1. Login at <a href="https://apps.twitter.com/"><strong><span style="color: #0000ff;">https://apps.twitter.com/</span> </strong></a>with your Twitter account and click on <span style="color: #008000;"><strong>&#8216;Create App&#8217;</strong></span>.</p> 
<p>2. Fill in the application details and get keys and tokens related to your project, then click on <span style="color: #0000ff;"><strong>&#8216;App Settings</strong></span>&#8216;.</p> 
<p><img class="alignnone size-full wp-image-3087" src="https://c1ctech.com/wp-content/uploads/2022/02/create_app-e1644659272732.png" alt="" width="585" height="377" /></p> 
<p> ;</p> 
<p>3. Under <span style="color: #0000ff;"><strong>User authentication settings</strong></span> click on <span style="color: #008000;"><strong>set up</strong></span>.</p> 
<p>4. Enable the authentication methods according to your requirement as shown below:</p> 
<p><img class="alignnone wp-image-3083" src="https://c1ctech.com/wp-content/uploads/2022/02/auth_page.png" alt="" width="603" height="444" /></p> 
<p>5. Enter App type, enable <span style="color: #008000;"><strong>request email from users</strong></span> only if you want to request user&#8217;s email in your app and also select app permission according to your requirement.</p> 
<p><img class="alignnone wp-image-3084" src="https://c1ctech.com/wp-content/uploads/2022/02/auth_next.png" alt="" width="582" height="529" /></p> 
<p>6. Enter your website URL and enter <span style="color: #008000;"><span style="color: #0000ff;"><strong>twittersdk:// </strong></span><span style="color: #333333;">in</span><strong> Callback URI </strong><span style="color: #333333;">field</span></span> which is mandatory in order to enable authentication through Twitter.</p> 
<p><img class="alignnone wp-image-3085" src="https://c1ctech.com/wp-content/uploads/2022/02/auth_3.png" alt="" width="642" height="290" /></p> 
<p>7. Fill in the below two properties which are mandatory when you enable &#8220;<span style="color: #008000;"><strong>Request email from users&#8221;</strong></span> and then click on <strong><span style="color: #008000;">save</span></strong>.</p> 
<p><img class="alignnone wp-image-3086 size-full" src="https://c1ctech.com/wp-content/uploads/2022/02/auth_4-e1644659618467.png" alt="" width="803" height="349" /></p> 
<h4><strong><span style="color: #000080;">Creating new project</span></strong></h4> 
<p>1 . Create a new project by going to <span style="color: #008000;"><strong>File ⇒ New Android Project</strong></span>, select <span style="color: #008000;"><strong>Empty</strong></span> Activity, provide <span style="color: #008000;"><strong>app</strong></span> name, select language to <span style="color: #008000;"><strong>kotlin</strong></span> and then finally click on <span style="color: #008000;"><strong>finish</strong></span>.</p> 
<p>2 . Open app-level build.gradle file and add the below libraries under dependencies section and then click on <span style="color: #0000ff;"><strong>Sync Now</strong></span>.:</p> 
<pre>dependencies {<br /><strong><span style="color: #008000;"> //Include all the Twitter APIs</span></strong><br /><strong> //compile 'com.twitter.sdk.android:twitter:3.1.1'</strong><br /><br /><strong><span style="color: #008000;"> //include only the necessary dependencies to avoid the Android dex limit</span></strong><br /> implementation 'com.twitter.sdk.android:twitter-core:3.1.1'<br /><br /><strong><span style="color: #008000;"> //dependency to load image url over image view</span></strong><br /> implementation 'com.squareup.picasso:picasso:2.5.2'<br />}</pre> 
<p>3 . Open the AndroidManifest.xml file and add the Internet permission above the application element.</p> 
<pre><strong><span style="color: #008000;"> <;uses-permission android:name="android.permission.INTERNET" />;</span></strong></pre> 
<p>4. Open your<span style="color: #008000;"> <strong>/app/res/values/strings.xml</strong></span> file and place the &#8216;Consumer Key&#8217; and &#8216;Consumer Secret&#8217; of our app generated by Twitter:</p> 
<pre><;resources>;<br /> <strong><span style="color: #008000;"> <;!--</span></strong><br /><strong><span style="color: #008000;"> place here CONSUMER_KEY(API Key) and CONSUMER_SECRET(API Secret)</span></strong><br /><strong><span style="color: #008000;"> -->;</span></strong><br /> <;string name="com.twitter.sdk.android.CONSUMER_KEY">;ENTER YOUR CONSUMER_KEY<;/string>;<br /> <;string name="com.twitter.sdk.android.CONSUMER_SECRET">;ENTER YOUR CONSUMER_SECRET<;/string>;<br /><br /><;/resources>;</pre> 
<h4><span style="color: #000080;"><strong>Creating the Layout File</strong></span></h4> 
<p>5. The below layout file consists of a <strong><span style="color: #008000;">TwitterLoginButton,</span></strong> an ImageView (to show user profile picture), and a <strong><span style="color: #008000;">TextView</span></strong> (to show user info).</p> 
<p><strong><span style="color: #0000ff;">activity_main.xml</span></strong></p> 
<pre><;?xml version="1.0" encoding="utf-8"?>;<br /><;androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> xmlns:app="http://schemas.android.com/apk/res-auto"<br /> xmlns:tools="http://schemas.android.com/tools"<br /> android:layout_width="match_parent"<br /> android:layout_height="match_parent"<br /> tools:context=".MainActivity">;<br /><br /> <;com.twitter.sdk.android.core.identity.TwitterLoginButton<br /> android:id="@+id/login_button"<br /> android:layout_width="wrap_content"<br /> android:layout_height="wrap_content"<br /> android:layout_alignParentBottom="true"<br /> android:layout_centerHorizontal="true"<br /> android:layout_centerVertical="true"<br /> android:layout_marginBottom="50dp"<br /> app:layout_constraintBottom_toBottomOf="parent"<br /> app:layout_constraintEnd_toEndOf="parent"<br /> app:layout_constraintStart_toStartOf="parent" />;<br /><br /> <;ImageView<br /> android:id="@+id/userImage"<br /> android:layout_width="100dp"<br /> android:layout_height="100dp"<br /> android:layout_marginTop="50dp"<br /> android:scaleType="center"<br /> app:layout_constraintEnd_toEndOf="parent"<br /> app:layout_constraintStart_toStartOf="parent"<br /> app:layout_constraintTop_toTopOf="parent" />;<br /><br /> <;TextView<br /> android:id="@+id/userDetail"<br /> android:layout_width="match_parent"<br /> android:layout_height="wrap_content"<br /> android:layout_marginTop="20dp"<br /> android:padding="5dp"<br /> android:text=""<br /> android:textColor="@color/purple_500"<br /> android:textSize="21sp"<br /> app:layout_constraintEnd_toEndOf="parent"<br /> app:layout_constraintHorizontal_bias="0.5"<br /> app:layout_constraintStart_toStartOf="parent"<br /> app:layout_constraintTop_toBottomOf="@+id/userImage" />;<br /><br /><;/androidx.constraintlayout.widget.ConstraintLayout>;</pre> 
<h4><span style="color: #000080;"><strong>Creating the Application class</strong></span></h4> 
<p>6. Inside the MyApplication class initialize the TwitterKit SDK.</p> 
<p><strong><span style="color: #0000ff;">MyApplication.kt</span></strong></p> 
<pre>class MyApplication: Application() {<br /><br /> override fun onCreate() {<br /> super.onCreate()<br /><br /><strong><span style="color: #008000;"> // Entry point to initialize the TwitterKit SDK.</span></strong><br /> Twitter.initialize(this)<br /> }<br />}</pre> 
<p>7. Open the AndroidManifest.xml file and add the application name property as shown below:</p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>
 
<pre><;application<br /><strong><span style="color: #0000ff;">android:name=".MyApplication"</span></strong><br />....<br /><;/application>;</pre> 
<div id="quads-ad2" class="quads-location quads-ad2"> 
<h4><span style="color: #000080;"><strong>Creating the MainActivity File</strong></span></h4> 
<p>8. The <span style="color: #008000;"><strong>MainActivity.kt</strong></span> file contains the below code:</p> 
<p><span style="color: #0000ff;"><strong>MainActivity.kt</strong></span></p> 
<pre>package com.c1ctech.twitloginexp<br /><br />import androidx.appcompat.app.AppCompatActivity<br />import android.os.Bundle<br />import com.c1ctech.twitloginexp.databinding.ActivityMainBinding<br />import android.widget.Toast<br />import com.twitter.sdk.android.core.*<br />import android.content.Intent<br />import com.squareup.picasso.Picasso<br />import com.twitter.sdk.android.core.models.User<br /><br />class MainActivity : AppCompatActivity() {<br /><br /> lateinit var activityMainBinding: ActivityMainBinding<br /><br /> override fun onCreate(savedInstanceState: Bundle?) {<br /> super.onCreate(savedInstanceState)<br /><br /> activityMainBinding = ActivityMainBinding.inflate(layoutInflater)<br /><br /> setContentView(activityMainBinding.root)<br /><br /> loginWithTwitter()<br /> }<br /><br /> private fun loginWithTwitter() {<br /><br /><strong><span style="color: #008000;"> //user is not authenticated</span></strong><br /> if (getTwitterSession() == null) {<br /><br /><strong><span style="color: #008000;"> //Sets the Callback to invoke when login completes.</span></strong><br /> activityMainBinding.loginButton.setCallback(object : Callback<;TwitterSession?>;() {<br /><br /><strong><span style="color: #008000;"> //Unsuccessful call due to network failure, non-2XX status code, or unexpected exception.</span></strong><br /> override fun failure(exception: TwitterException?) {<br /> Toast.makeText(<br /> applicationContext,<br /> "Login failed: " + exception,<br /> Toast.LENGTH_LONG<br /> ).show()<br /> }<br /><br /><strong><span style="color: #008000;"> //Called when call completes successfully.</span></strong><br /> override fun success(result: Result<;TwitterSession?>;?) {<br /> Toast.makeText(applicationContext, "Login successful", Toast.LENGTH_LONG).show()<br /> val twitterSession = result?.data<br /><br /><strong><span style="color: #008000;"> //get secret and token from twitterSession</span></strong><br /> <strong> /*val token = twitterSession?.authToken?.token</strong><br /><strong> val secret = twitterSession?.authToken?.secret*/</strong><br /><br /> if (twitterSession != null) {<br /><strong><span style="color: #008000;"> //fetch user twitter info and display it on screen</span></strong><br /> fetchUserTwitterInfo()<br /> }<br /> }<br /> })<br /> } else {<br /> Toast.makeText(this, "User already authenticated", Toast.LENGTH_SHORT).show()<br /> fetchUserTwitterInfo()<br /> }<br /> }<br /><br /><strong><span style="color: #008000;"> //return the active session if available</span></strong><br /> private fun getTwitterSession(): TwitterSession? {<br /> val twitterSession = TwitterCore.getInstance().sessionManager.activeSession<br /> return twitterSession<br /> }<br /><br /><strong><span style="color: #008000;"> // this method will provide you User model which contains all user information</span></strong><br /> fun fetchUserTwitterInfo() {<br /><br /><strong><span style="color: #008000;"> //fetch twitter image with other information if user is already authenticated</span></strong><br /> if (getTwitterSession() != null) {<br /><br /><strong><span style="color: #008000;"> //initialize twitter api client</span></strong><br /> val twitterApiClient = TwitterCore.getInstance().apiClient<br /><br /><strong><span style="color: #008000;"> //pass includeEmail : true if you want to fetch Email as well</span></strong><br /> val call =<br /> twitterApiClient.accountService.verifyCredentials(true, false, true)<br /> call.enqueue(object : Callback<;User?>;() {<br /><br /><strong><span style="color: #008000;"> // Called when call completes successfully.</span></strong><br /> override fun success(result: Result<;User?>;?) {<br /><br /> val user = result?.data<br /> activityMainBinding.userDetail.text =<br /> """<br /> User Id : ${user?.id}<br /> User Name : ${user?.name}<br /> Email Id : ${user?.email}<br /> Screen Name : ${user?.screenName}<br /> """.trimIndent()<br /><br /> var imageProfileUrl = user?.profileImageUrl<br /><br /> <strong><span style="color: #008000;">//NOTE : User profile provided by twitter is very small in size</span></strong><br /><strong><span style="color: #008000;"> //Link : https://developer.twitter.com/en/docs/accounts-and-users/user-profile-images-and-banners</span></strong><br /><strong><span style="color: #008000;"> //so if you want to get bigger size image then do the following:</span></strong><br /> imageProfileUrl = imageProfileUrl?.replace("_normal", "")<br /><br /><strong><span style="color: #008000;"> //load image using Picasso</span></strong><br /> Picasso.with(this@MainActivity)<br /> .load(imageProfileUrl)<br /> .placeholder(R.drawable.placeholder)<br /> .into(activityMainBinding.userImage)<br /> }<br /><br /><strong><span style="color: #008000;"> // Unsuccessful call due to unexpected exception.</span></strong><br /> override fun failure(exception: TwitterException?) {<br /> Toast.makeText(<br /> this@MainActivity,<br /> exception?.message,<br /> Toast.LENGTH_SHORT<br /> ).show()<br /> }<br /><br /> })<br /> } else {<br /><strong><span style="color: #008000;"> //if user is not authenticated first ask user to do authentication</span></strong><br /> Toast.makeText(this, "User is not authenticated.", Toast.LENGTH_SHORT)<br /> .show()<br /> }<br /> }<br /><br /> override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {<br /><br /> super.onActivityResult(requestCode, resultCode, data)<br /><br /><strong><span style="color: #008000;"> // Pass the activity result to the login button.</span></strong><br /> activityMainBinding.loginButton.onActivityResult(requestCode, resultCode, data)<br /> }<br />}</pre> 
<p>In the above code,</p> 
<ul> 
<li><span style="color: #008000;"><strong>getTwitterSession()</strong></span> method will return the active session if available.</li> 
<li>When a user successfully logs in, the loginButton.onActivityResult() will invoke, which will pass the response to the registered callback.</li> 
<li>If the login <span style="color: #008000;"><strong>succeeds</strong></span>, the <strong><span style="color: #008000;">TwitterSession</span></strong> parameter has the <strong>userId, userName, authToken (contains token and secret)</strong>, etc.</li> 
<li>If the TwitterSession parameter is not null, then we will fetch the user&#8217;s Twitter info and display it on the screen.</li> 
<li>If the login <strong><span style="color: #008000;">failed</span>, </strong>the callback<strong><span style="color: #008000;"> failure()</span></strong> method will call with an exception.</li> 
</ul> 
<p>When you run the app it will look like this:</p> 
<p><img class="alignnone wp-image-3079" src="https://c1ctech.com/wp-content/uploads/2022/02/Screenshot_2022-02-10-13-59-28-932_com.c1ctech.twitloginexp-473x1024.png" alt="" width="314" height="680" /></p> 
<p>When a user clicks on <span style="color: #0000ff;"><strong>Log in with Twitter</strong></span> button, it will ask for entering the user&#8217;s Twitter email/username and password then click on &#8220;<span style="color: #0000ff;"><strong>Authorize app&#8221;</strong></span>.</p> 
<p><img class="alignnone wp-image-3077" src="https://c1ctech.com/wp-content/uploads/2022/02/Screenshot_2022-02-10-14-01-53-172_com.c1ctech.twitloginexp-473x1024.png" alt="" width="384" height="831" /></p> 
</div> 
<p>When a user successfully logs in, it will show the user info as shown below:</p> 
<p><img class="alignnone wp-image-3078" src="https://c1ctech.com/wp-content/uploads/2022/02/Screenshot_2022-02-10-14-02-23-665_com.c1ctech.twitloginexp-473x1024.png" alt="" width="366" height="792" />

