android facebook facebook integration How-tos Integrate Kotlin Other Android Tutorials social network Tech tutorial twitter twitter integration

Social Network Integration on Android

Social Network Integration on Android

Social Network Integration on Android

Many cellular apps require a consumer to create an account or to join a service in an effort to use them. From a consumer’s perspective, this may be considerably troublesome or annoying, and it’s not all the time the perfect consumer expertise.

So how are you going to overcome this when constructing your app? To offer customers a seamless expertise, you may give them the power to sign up to your app with only a single faucet of a button, utilizing certainly one of their social networking accounts, e.g., Fb or Twitter.

On this tutorial, you’ll discover ways to combine a consumer’s Fb and Twitter accounts into your Android app to permit them to log in and in addition share posts out of your app into their social networking account.

Getting Began

Use the Obtain Supplies hyperlink on the prime or backside of this tutorial to obtain and extract the Starter Undertaking for this tutorial.

Subsequent, open Android Studio three.1.three or later, and select Open an present Android Studio venture from the welcome display or File > Open type the menu. Open the folder root folder of the Sharetastic starter challenge.

You’ll be working on an app referred to as Sharetastic, which permits a consumer to share a standing replace to Fb or a tweet to Twitter.

Construct and run the venture and also you’ll see the login display for the app:

Starter project

As of now, the app does nothing. On this tutorial, you’ll undergo it step-by-step and full the social community integration.

Connecting With Fb

To attach your app to Fb, you’ll want an lively Fb account with which you’ll create an app to get a Fb App ID.

Making a Fb App ID on Builders Portal & Setting Up

Go to the Fb Builders Portal (log in together with your Fb account if wanted).

On this web page, you’ll see an choice to Add a New App. Click on the button and also you’ll then have to create a Fb App ID should you haven’t already:

Create Facebook App ID

Enter Sharetastic within the Show Identify subject and enter your e-mail handle within the Contact E mail area, then click on Create App ID. Fb will immediate you with a captcha dialog; full the request and click on Submit.

Fb will then direct you to a different web page:

Setup Facebook Login

Click on on Set Up on the Fb Login element. Then, from the brand new web page containing the platform choices, choose Android.

You’ll then see the next web page with the steps to construct your Android undertaking:

Steps to build

At this level, you’ll skip steps 1 and a couple of as a result of they’ve already been accomplished for you within the starter undertaking. Even so, it’s good to know what they’re:

Step 1 consists of downloading the Fb SDK, and Step 2 tells you easy methods to import it into the challenge. Right here, Gradle shall be used to sync the Fb SDK moderately than manually downloading the SDK, which you’ll be able to see within the app module construct.gradle file:

implementation ‘[four,5)’

In Step three, you’ll add your Package deal identify com.raywenderlich.sharetastic and default Exercise identify com.raywenderlich.sharetastic.MainActivity.

Facebook Step 3

Click on on Save after which Proceed (you could have to additionally affirm that your app shouldn’t be but within the Play Retailer).

For Step four, it’s essential create a Improvement Key Hash and in addition a Launch Key Hash in case your app is reside. A key hash is a 28-character-long string, which Fb makes use of to confirm the communication between your app and Fb.

Key Hashes?

A key hash may be generated by typing the next command within the terminal:

For Mac and Linux:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

For Home windows:

Issues will not be that straightforward right here. First, you want to have keytool from the JDK, Secondly, get the openssl library right here.

keytool -exportcert -alias androiddebugkey -keystore “C:UsersUSERNAME.androiddebug.keystore” | “PATH_TO_OPENSSL_LIBRARYbinopenssl” sha1 -binary | “PATH_TO_OPENSSL_LIBRARYbinopenssl” base64

Lastly, after producing your Key Hash, paste it within the part offered within the fourth step.

Paste key hash

Click on Save then Proceed.

For Step 5 on Single Signal On, for those who’re working on a unique app that’s utilizing notifications, you need need to set it to Sure, however, for now, depart it set to No and click on on Save, then Subsequent.

Single Sign On

Now, for Step 6, open up strings.xml within the app/res/values folder, and paste the next after updating the placeholders with the values offered by Fb:

<string identify=”facebook_app_id”>Your-App-ID</string>
<string identify=”fb_login_protocol_scheme”>fbYour-App-ID</string>

Then, open AndroidManifest.xml and add the permission for accessing the Web:

<uses-permission android:identify=”android.permission.INTERNET”/>

Moreover, beneath the appliance tag, paste the wanted Fb meta-data and actions:

<meta-data android:identify=”com.facebook.sdk.ApplicationId”

<exercise android:identify=”com.facebook.FacebookActivity”
android:label=”@string/app_name” />
<motion android:identify=”android.intent.action.VIEW” />
<class android:identify=”android.intent.category.DEFAULT” />
<class android:identify=”android.intent.category.BROWSABLE” />
<knowledge android:scheme=”@string/fb_login_protocol_scheme” />

Lastly, you’re accomplished setting issues up from the Fb developer console! The remaining steps you’ll have to login are dealt with within the subsequent part.

Now it’s time transfer on to writing some code.

Facebook setup complete

Log in With Fb

Open up the primary format file activity_main.xml and add a Fb login button under the TextView:

app:layout_constraintLeft_toLeftOf=”parent” app:layout_constraintRight_toRightOf=”parent”
app:layout_constraintVertical_bias=”0.58″ />

In MainActivity, create the next constants on the prime of the category:

val EMAIL = “email”
val PUBLIC_PROFILE = “public_profile”
val USER_PERMISSION = “user_friends”

Contained in the empty technique facebookSetup(), add the next code:

callbackManager = CallbackManager.Manufacturing unit.create()
facebookLoginButton.setReadPermissions(Arrays.asList(EMAIL, PUBLIC_PROFILE, USER_PERMISSION))
facebookLoginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult>
override enjoyable onSuccess(loginResult: LoginResult)

override enjoyable onCancel()

override enjoyable onError(exception: FacebookException)
Toast.makeText(context,exception.localizedMessage, Toast.LENGTH_SHORT).present()


This code first initializes the CallbackManager Fb property that was declared however uninitialized within the starter challenge. It then provides a click on listener for the Fb login button. Inside the press listener, it supplies the permissions wanted to learn the e-mail, public profile and buddies of the consumer. It additionally logs within the consumer by returning the AccessToken.

Then in onActivityResult(), cross the outcome onto the CallbackManager:

callbackManager.onActivityResult(requestCode, resultCode, knowledge)

Within the onSuccess of the callback, you’ll get the consumer’s profile through the use of Fb’s Graph API. You’ll then ship the consumer to the Share display. First, we have to speak to the Graph API.

Consumer Profile from the Graph API

You’ll now create a Kotlin object, whose sole function will probably be to include the helper strategies to hook up with the Graph API.

Create an object referred to as Helper in a brand new package deal com.raywenderlich.sharetastic.util.

As soon as created, write the tactic getFacebookUserProfileWithGraphApi() inside it:

object Helper

enjoyable getFacebookUserProfileWithGraphApi(context: Context)

if (AccessToken.getCurrentAccessToken() != null)
val exercise = context as Exercise
val request = GraphRequest.newMeRequest(
) jsonObject, _ ->
val e-mail = jsonObject?.get(“email”)?.toString() ?: “”
val identify = jsonObject.get(“name”).toString()
val profileObjectImage = jsonObject?.getJSONObject(“picture”)?.getJSONObject(“data”)?.get(“url”).toString()

val parameters = Bundle()
parameters.putString(“fields”, “id,name,link,picture.type(large), email”)
request.parameters = parameters

This technique makes use of a name to GraphRequest.newMeRequest() to fetch the userid, identify, image and e mail of the consumer who’s presently logged in.

To maintain issues clear, create a package deal com.raywenderlich.sharetastic.mannequin and create a category within the package deal referred to as UserModel to include the consumer’s knowledge after the Graph API returns the outcomes.

Your UserModel class would look one thing like this:

class UserModel(val identify: String, val userName: String, val profilePictureUrl: String, val socialNetwork: SocialNetwork) : Serializable

enum class SocialNetwork
Fb, Twitter

I’ve created the enum class SocialNetwork in the identical class; you can create a separate file for that if you want. The enum class is just for figuring out which social community account the consumer is presently logged in with.

Head again to Helper the place you’ll now write the tactic that may assist in sending the consumer to the Share display.

enjoyable startShareActivity(context: Context, consumer: UserModel)
val exercise = context as Exercise
val intent = Intent(context,
intent.putExtra(“user”, consumer)

This code takes the passed-in UserModel and sends it to the ShareActivity.

Return to the tactic getFacebookUserProfileWithGraphApi() and after the road:

val profileObjectImage = jsonObject?.getJSONObject(“picture”)?.getJSONObject(“data”)?.get(“url”).toString() ?: “”

add the next:

val consumer = UserModel(identify, e-mail, profileObjectImage, SocialNetwork.Fb)
startShareActivity(context, consumer)

These strains convert the consumer’s information to a UserModel and cross it into the tactic startShareActivity().

After finishing that, return to MainActivity. Within the onSuccess inside facebookSetup(), write:


The consumer ought to solely be despatched to the Share display when the consumer has a legitimate AccessToken, and this could occur solely within the onSuccess block of code.

Moreover, you might want to arrange a couple of issues within the ShareActivity.

Create a UserModel property within the class:

lateinit var consumer: UserModel

And inside onCreate(), add:

consumer = intent.extras.get(“user”) as UserModel

This piece of code is getting the handed in UserModel from the Intent technique and passing the info to a brand new technique setData().

The setData() technique merely units up the info within the UI, and consists of conditionals that take barely totally different actions relying on whether or not the logged in community is Fb or Twitter.

enjoyable setData(consumer: UserModel)
nameTextView.textual content = consumer.identify
userNameTextView.textual content =
if (consumer.socialNetwork == SocialNetwork.Twitter) “@$user.userName”
else consumer.userName
connectedWithTextView.textual content =
if (consumer.socialNetwork == SocialNetwork.Twitter) “$connectedWithTextView.text Twitter”
else “$connectedWithTextView.text Facebook”
characterLimitTextView.visibility =
if (consumer.socialNetwork == SocialNetwork.Twitter) View.VISIBLE
else View.GONE
postButton.textual content =
if (consumer.socialNetwork == SocialNetwork.Twitter) “POST”
postEditText.visibility = View.GONE

Now, run your app then faucet on Proceed with Fb. You’ll be requested to provide your app the permission to entry the knowledge. After this step, you’ll be redirected to the next display:

Successful login

You’ve efficiently logged in!

Sharing on Fb

It’s time to maneuver on to posting a standing to Fb. For this, it’s essential to change a couple of issues.

Fb lately modified its documentation and has eliminated the permission that was as soon as required for the utilizing the Graph API to share one thing on a consumer’s timeline. The choice for that’s now utilizing the Fb Share SDK.

Open the app construct.gradle file, and add the next dependency in it:

implementation ‘[four,5)’

Moreover, in your AndroiManifest.xml add the next line inside the software tag:

<supplier android:authorities=”[email protected]/facebook_app_id”

Now, open the ShareActivity class and write the tactic for posting standing to Fb:

enjoyable postStatusToFacebook()
val builder = AlertDialog.Builder(this)
builder.setTitle(“Share Link”)

val enter = EditText([email protected])
val lp = LinearLayout.LayoutParams(
enter.layoutParams = lp

builder.setPositiveButton(android.R.string.okay) dialog, p1 ->
val hyperlink = enter.textual content
var isValid = true
if (hyperlink.isBlank())
isValid = false

if (isValid)
val content material = ShareLinkContent.Builder()
ShareDialog.present(this, content material)


builder.setNegativeButton(android.R.string.cancel) dialog, p1 ->


This code will current an alert dialog to permit the consumer to enter a hyperlink to share, after which present the consumer the Fb share dialog. We’re not doing any validation on the hyperlink aside from to examine that it’s not clean; you’d need to do some validation to ensure it’s a legitimate URL.

In later variations of the Fb Share SDK, together with the one you’re utilizing in Sharetastic, you need to present some sort of content material to share. Your choices are hyperlinks, photographs, movies, and different multimedia. See the Fb Share SDK documentation for extra particulars.

Subsequent, within the postButtonAction() technique, contained in the setOnClickListener, add a name to the brand new perform:


Construct and run the app once more. You’ll have to faucet logout on the Fb button and re-connect. In a manufacturing app, you’ll need to saved the logged in state of the consumer in order that they don’t should log in once more.

Click on on CREATE POST. Now, attempt posting one thing to Fb:

Share link

Facebook dialog

After urgent POST, go and verify the Fb app.

Facebook app

Hurray! Your standing is posted to Fb.


Logging Out of Fb

Logging out is just a one-line code, however, for logging out, you might want to carry out two further duties. You’ll now write a way in your ShareActivity that’ll do these duties:

enjoyable sendToMainActivity()
val intent = Intent(this,

Going over the above: the primary line of code permits a consumer to sign off of Fb. The remainder of the strains end the present exercise and take a consumer to MainActivity. Lastly, name this technique contained in the onOptionsItemSelected like this: ->
return true

When you faucet the Logout button on top-right of the Share display, you’ll be logged out from the app and brought to the House display.

Now, let’s join the app with Twitter.

Connecting With Twitter

Like Fb, you want a working Twitter account with a view to combine Twitter into your app, Twitter supplies a Shopper Key and Shopper Secret for communication.

Making a Twitter App on Developer Portal

Login to Twitter in a browser and head to Twitter’s Software Administration Portal and click on on Create New App.

Create new Twitter app

Full the required fields with the suitable info (you’ll want to make use of a singular identify like Sharetastic + your initials, and also you additionally should present a Privateness Coverage URL and Phrases of Service URL with a view to comply with alongside, however these may be placeholders like then click on Create your Twitter software.

You’ll be taken to the next web page:

Details page

I needed to identify the app Share-tastic as a result of Sharetastic wasn’t obtainable. :]

Copy the Shopper Key and Shopper Secret from the Keys and Entry Tokens tab and paste them into the strings.xml with the names Twitter_CONSUMER_KEY and Twitter_CONSUMER_SECRET, respectively.

Then click on on the Permissions tab.

Permissions tab

If you wish to get consumer’s e-mail on the time of login, you need to verify the choice that claims Request e mail addresses from customers then click on on Replace Settings.

Setting Up

After ending the creation of the app on the Twitter developer portal, you’ll now transfer on and add the Twitter Package dependency.

Including Twitter Package Dependency

Word: This step might be skipped as a result of it’s already carried out within the Starter Venture

There are numerous dependencies offered by Twitter like Twitter Core, Tweet UI, Tweet Composer, and Twitter Mopub. For now, stick to Twitter Core as a result of that’s the one dependency you want for this tutorial.

implementation ‘’

Paste the above dependency within the app construct.gradle file and let the challenge sync.

Initializing Twitter Package

Create a CustomApplication class extending from Software beneath a brand new package deal root. Override the onCreate() of the Software class as follows:

class CustomApplication : Software()
override enjoyable onCreate()

val config = TwitterConfig.Builder(this)

Then open AndroidManifest.xml and contained in the tag software, paste the next snippet.


You’re finished establishing now and are able to dive into writing some Twitter code!

Log in With Twitter

Add a Twitter login button to activity_main.xml:

app:layout_constraintVertical_bias=”0.1″ />

Open MainActivity and contained in the twitterSetup() technique, add the next:

twitterLoginButton.callback = object : Callback<TwitterSession>()
override enjoyable success(end result: Outcome<TwitterSession>)

override enjoyable failure(exception: TwitterException)
Toast.makeText(context,exception.localizedMessage, Toast.LENGTH_SHORT).present()

And within the onActivityResult() technique, add the next line:

twitterLoginButton.onActivityResult(requestCode, resultCode, knowledge)

Like the tactic you wrote that fetches the consumer information after Fb’s login is full, you’ll want to write an identical technique for Twitter that will get the consumer’s information at login.

Open the Helper file and write the next technique:

enjoyable getTwitterUserProfileWthTwitterCoreApi(
context: Context, session: TwitterSession)

.verifyCredentials(true, true, false)
.enqueue(object : Callback<Consumer>()
override enjoyable success(outcome: Outcome<Consumer>)
val identify = outcome.knowledge.identify
val userName = end result.knowledge.screenName
val profileImageUrl = end“_normal”, “”)
val consumer = UserModel(identify, userName, profileImageUrl, SocialNetwork.Twitter)
startShareActivity(context, consumer)

override enjoyable failure(exception: TwitterException)
Toast.makeText(context, exception.localizedMessage, Toast.LENGTH_SHORT).present()


You’re utilizing TwitterCore to authenticate the consumer after which going to the share display on a profitable authentication.

Subsequent, open MainActivity and within the success a part of the twitterLoginButton callback, add:

Helper.getTwitterUserProfileWthTwitterCoreApi(context, outcome.knowledge)

Now, construct and run your venture and faucet on Log in with Twitter. You’ll must be operating Sharetastic on a tool or emulator that has the Twitter app put in and through which you’re logged in.

You’ll be proven a display to simply accept connecting your Twitter account to Sharetastic, and after you permit it, you’ll efficiently log in and be taken to the Share display.

Twitter share screen

A Tweet for the Tweeps

Earlier than posting a tweet, make the app slightly extra interactive by putting the Twitter’s character restrict — i.e., 240 — and alter the TextView rely positioned on the highest proper with respect to the variety of characters written within the posting TextView.

Write a way onTextChangeListener inside ShareActivity:

enjoyable onTextChangeListener()
postEditText.addTextChangedListener(object : TextWatcher
override enjoyable afterTextChanged(s: Editable)
characterLimitTextView.textual content = “$s.length/240″

override enjoyable beforeTextChanged(s: CharSequence, begin: Int,
rely: Int, after: Int)

override enjoyable onTextChanged(s: CharSequence, begin: Int,
earlier than: Int, rely: Int)


This code is dealing with the character rely change logic at runtime.

Moreover, change the setData() technique of ShareActivity by changing the road that units the postEditText to be GONE with the next code:

if (consumer.socialNetwork == SocialNetwork.Twitter)
postEditText.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(240))
postEditText.visibility = View.GONE

Right here, a personality restrict is utilized on the TextView to cease a consumer from writing greater than 240 characters.

Now, transfer on to posting a tweet. For that, you’ll write one other technique:

enjoyable postATweet(message: String)
val statusesService = TwitterCore.getInstance().apiClient.statusesService
val context = this
statusesService.replace(message, null, null, null, null, null, null, null, null)
.enqueue(object : Callback<Tweet>()
override enjoyable success(outcome: Outcome<Tweet>)

override enjoyable failure(exception: TwitterException)


Lastly, you have to tweak the postButtonAction() technique just a little bit:

enjoyable postButtonAction()
postButton.setOnClickListener view ->
if (postEditText.textual content.toString().isBlank() && consumer.socialNetwork == SocialNetwork.Twitter)
Toast.makeText(this, R.string.cannot_be_empty, Toast.LENGTH_SHORT).present()
else if (consumer.socialNetwork == SocialNetwork.Fb)
postATweet(postEditText.textual content.toString())

Now the time has come during which you publish your first tweet!

Construct and run the app once more. Like earlier than, because you’re not saving the authenticated state of the consumer, you’ll have to login to Twitter once more.

After logging in write, say, Hiya Twitter from Sharetastic!

Share to Twitter

Then faucet on POST and open the Twitter app.

Twitter appYou possibly can lastly see your tweet.

Feels Good

Feels good, doesn’t it?

Logging Out of Twitter

Like Fb, logging out is fairly easy. All it’s a must to do is change the tactic sendToMainActivity() in ShareActivity to the next:

if (consumer.socialNetwork == SocialNetwork.Fb)

val intent = Intent(this,

The one change right here is that the Twitter session is being cleared.

When you run the app once more, you’ll have the ability to sign off from Twitter as properly. :]

The place to Go From Right here?

The Ultimate Undertaking for this tutorial might be discovered within the Obtain Supplies hyperlink on the prime or backside of this tutorial. In the event you attempt to construct the ultimate challenge, please remember to add in your personal Fb and Twitter app ID’s and keys.

You now know find out how to authenticate a consumer into Fb and Twitter, submit content material to every, and log a consumer out of every.

As was talked about within the tutorial, in your app you’re going to need to persist the state of the logged in consumer, in order that the consumer doesn’t need to log in to Fb or Twitter each time the app runs. Attempt saving the consumer state as a problem, when you’ve labored your method via the tutorial. If the consumer is logged in, take them proper to the share display.

If you wish to discover extra concerning the Fb SDK and TwitterKit, go to the assets under:

In case you have any questions or feedback, please tell us within the dialogue under!

Obtain Supplies

(perform(d, s, id)
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); = id;
js.src = “//”;
fjs.parentNode.insertBefore(js, fjs);
(doc, ‘script’, ‘facebook-jssdk’));