Social Network Integration on Android

Learn how to let your users authenticate into your app using Facebook and Twitter, and see how to make posts to both social networks. By Aaqib Hussain.

Leave a rating/review
Download materials
Save for later
Share

Many mobile apps require a user to create an account or to sign up for a service in order to use them. From a user’s point of view, this can be somewhat troublesome or annoying, and it’s not always the best user experience.

So how can you overcome this when building your app? To give users a seamless experience, you can give them the ability to sign in to your app with just a single tap of a button, using one of their social networking accounts, e.g., Facebook or Twitter.

In this tutorial, you’ll learn how to integrate a user’s Facebook and Twitter accounts into your Android app to allow them to log in and also share posts from your app into their social networking account.

Getting Started

Use the Download Materials link at the top or bottom of this tutorial to download and extract the Starter Project for this tutorial.

Next, open Android Studio 3.1.3 or later, and choose Open an existing Android Studio project from the welcome screen or File > Open form the menu. Open the folder root folder of the Sharetastic starter project.

You’ll be working on an app called Sharetastic, which allows a user to share a status update to Facebook or a tweet to Twitter.

Build and run the project and you’ll see the login screen for the app:

Starter project

As of now, the app does nothing. In this tutorial, you’ll go through it step-by-step and complete the social network integration.

Connecting With Facebook

To connect your app to Facebook, you’ll need an active Facebook account with which you’ll create an app to get a Facebook App ID.

Creating a Facebook App ID on Developers Portal & Setting Up

Go to the Facebook Developers Portal (log in with your Facebook account if needed).

On this page, you’ll see an option to Add a New App. Click the button and you’ll then need to create a Facebook App ID if you haven’t already:

Create Facebook App ID

Enter Sharetastic in the Display Name field and enter your email address in the Contact Email field, then click Create App ID. Facebook will prompt you with a captcha dialog; complete the request and click Submit.

Facebook will then direct you to another page:

Setup Facebook Login

Click on Set Up on the Facebook Login component. Then, from the new page containing the platform options, select Android.

You’ll then see the following page with the steps to build your Android project:

Steps to build

At this point, you will skip steps 1 and 2 because they have already been completed for you in the starter project. Even so, it’s good to know what they are:

Step 1 includes downloading the Facebook SDK, and Step 2 tells you how to import it into the project. Here, Gradle will be used to sync the Facebook SDK rather than manually downloading the SDK, which you can see in the app module build.gradle file:

implementation 'com.facebook.android:facebook-login:[4,5)'

In Step 3, you’ll add your Package name com.raywenderlich.sharetastic and default Activity name com.raywenderlich.sharetastic.MainActivity.

Facebook Step 3

Click on Save and then Continue (you may need to also confirm that your app is not yet in the Play Store).

For Step 4, you need to create a Development Key Hash and also a Release Key Hash if your app is live. A key hash is a 28-character-long string, which Facebook uses to verify the communication between your app and Facebook.

Key Hashes?

A key hash can be generated by typing the following command in the terminal:

For Mac and Linux:

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

For Windows:

Things are not that simple here. First, you need to have keytool from the JDK, Secondly, get the openssl library here.

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\USERNAME\.android\debug.keystore" | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" sha1 -binary | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" base64

Finally, after generating your Key Hash, paste it in the section provided in the fourth step.

Paste key hash

Click Save then Continue.

For Step 5 on Single Sign On, if you’re working on a different app that is using notifications, you want want to set it to Yes, but, for now, leave it set to No and click on Save, then Next.

Single Sign On

Now, for Step 6, open up strings.xml in the app/res/values folder, and paste the following after updating the placeholders with the values provided by Facebook:

<string name="facebook_app_id">Your-App-ID</string>
<string name="fb_login_protocol_scheme">fbYour-App-ID</string>

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

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

Additionally, under the application tag, paste the needed Facebook meta-data and activities:

    <meta-data android:name="com.facebook.sdk.ApplicationId" 
        android:value="@string/facebook_app_id"/>
    
    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name" />
    <activity
        android:name="com.facebook.CustomTabActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>

Finally, you’re done setting things up from the Facebook developer console! The remaining steps you’ll need to login are handled in the next section.

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

Facebook setup complete

Log in With Facebook

Open up the main layout file activity_main.xml and add a Facebook login button below the TextView:

<com.facebook.login.widget.LoginButton
  android:id="@+id/facebookLoginButton"
  android:layout_width="wrap_content"
  android:layout_height="47dp"
  android:paddingBottom="15dp"
  android:paddingStart="10dp"
  android:paddingEnd="5dp"
  android:paddingTop="15dp"
  android:textSize="16sp"
  app:layout_constraintBottom_toBottomOf="parent"
  app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent"
  app:layout_constraintTop_toTopOf="parent"
  app:layout_constraintVertical_bias="0.58" />

In MainActivity, create the following constants at the top of the class:

val EMAIL = "email"
val PUBLIC_PROFILE = "public_profile"
val USER_PERMISSION = "user_friends"

Inside the empty method facebookSetup(), add the following code:

callbackManager = CallbackManager.Factory.create()
facebookLoginButton.setOnClickListener {
  facebookLoginButton.setReadPermissions(Arrays.asList(EMAIL, PUBLIC_PROFILE, USER_PERMISSION))
  facebookLoginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
    override fun onSuccess(loginResult: LoginResult) {

    }

    override fun onCancel() {

    }

    override fun onError(exception: FacebookException) {
      Toast.makeText(context,exception.localizedMessage, Toast.LENGTH_SHORT).show()
    }
  })
}

This code first initializes the CallbackManager Facebook property that was declared but uninitialized in the starter project. It then adds a click listener for the Facebook login button. Inside the click listener, it provides the permissions needed to read the email, public profile and friends of the user. It also logs in the user by returning the AccessToken.

Then in onActivityResult(), pass the result onto the CallbackManager:

callbackManager.onActivityResult(requestCode, resultCode, data)

In the onSuccess of the callback, you’ll get the user’s profile by using Facebook’s Graph API. You’ll then send the user to the Share screen. First, we need to talk to the Graph API.