Skip to Content

How to integrate Facebook login in your Android app using Android Studio?

How to integrate Facebook login in your Android app using Android Studio?

Facebook login integration allows users to easily sign in to your Android app using their Facebook account credentials. This saves users from creating a new account and remembering another set of login credentials. Integrating Facebook login has become very common in mobile apps for a seamless sign-in experience.

In this comprehensive guide, we will see step-by-step how to integrate Facebook login in an Android app using Android Studio.

Benefits of integrating Facebook login

Here are some of the benefits of integrating Facebook login in your Android app:

  • Quick and easy signup and login for users using their Facebook account
  • Saves users from creating and remembering another set of credentials
  • You can get basic profile information like name, profile pic, email, etc from the user’s Facebook account after login
  • Increase user engagement with social features
  • Higher conversion rates compared to email/password signups

Based on these advantages, you should consider adding Facebook login in your Android app alongside traditional email/password account signup.

Prerequisites

Before we start with the integration, you need the following:

  • Android Studio installed on your computer
  • An Android app project with empty Activity for login
  • Facebook developer account to get App ID and App Secret
  • Basic knowledge of Android development and Android Studio

Make sure you have these ready before proceeding further. The app project can be a new blank project or your existing project.

Let’s get started

The first thing you need to do is create a Facebook app to get App ID and App Secret. These credentials are required to integrate Facebook login in the Android app.

Step 1: Create Facebook app

Go to Facebook for Developers and login using your Facebook developer account. If you don’t have one, create one first.

After login, click on My Apps > Create App. Give a display name for your app and contact email and click on Create App ID. Accept the Facebook policies if you are creating an app for the first time.

This will create a new Facebook app with App ID and App Secret which you can find on the dashboard.

Make note of the App ID and App Secret which we’ll need later.

Step 2: Configure Facebook app settings

Next we need to configure some settings for our app:

  • Click on Add Platform on the dashboard and select Android.
  • Enter your app’s Package Name and default Android store listing name or create one if you don’t have it.
  • Under Key Hashes section, click on Add Key Hashes and enter the debug key hash of your Android app. This helps Facebook identify your app.

To get the debug key hash, run the following command in your Android Studio project directory:

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

Copy the key hash and enter it on the Facebook app dashboard.

That’s it for the Facebook app configuration. We are now ready to move on to integrating the login on Android.

Step 3: Add Facebook SDK dependency

The easiest way to integrate Facebook login is by adding the Facebook SDK dependency in your Android app. This gives access to the necessary classes for login integration.

Open the build.gradle file for your app module (not the project level file) and add the following dependency:

dependencies {
  // ... other dependencies
 
  //facebook sdk
  implementation 'com.facebook.android:facebook-login:[latest-version]' 
}  

Replace [latest-version] with the latest stable version of the Facebook SDK available.

Sync the gradle project after adding the dependency.

Step 4: Add FacebookAppID to resources

We need to provide our FacebookAppID that we got in Step 1 to the Facebook SDK. This is done by adding the following string resource to strings.xml file:

<string name="facebook_app_id">YOUR_FACEBOOK_APP_ID</string>

Replace YOUR_FACEBOOK_APP_ID with the actual App ID from your Facebook app dashboard.

Step 5: Configure Android manifest

Some configuration changes are needed in the Android manifest file to allow Facebook login integration:

  • Add Facebook Activity inside application tag
  <activity android:name="com.facebook.FacebookActivity"
  android:configChanges=
     "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
  android:label="@string/app_name" />
  
  • Add Facebook Application ID meta-data
  •   <meta-data android:name="com.facebook.sdk.ApplicationId" 
         android:value="@string/facebook_app_id"/>
      
  • Add Internet permission
  •   <uses-permission android:name="android.permission.INTERNET"/>
      

    These changes allow the Facebook SDK to do its job.

    Step 6: Implement Facebook login button

    We are now ready to implement the Facebook login button in our app. This will open up the Facebook login screen when users click on it.

    Open the layout XML file where you want to add the login button. For example, in the activity_main.xml layout.

    Add the following code to add Facebook login button:

    <com.facebook.login.widget.LoginButton
      android:id="@+id/login_button"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:layout_marginTop="30dp"
      android:layout_marginBottom="30dp"/>   
    

    This renders a Facebook login button UI component.

    Step 7: Handle login callback

    When users click on the Facebook login button, the flow will be handled by the Facebook SDK. Once login finishes, the result is given back via onActivityResult() callback in our Activity.

    So we need to override onActivityResult() method in our Activity class to handle the login callback:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    
      super.onActivityResult(requestCode, resultCode, data);
      
      // Pass the activity result to the Facebook SDK
      mCallbackManager.onActivityResult(requestCode, resultCode, data); 
    }
    

    We pass the activity result to the Facebook SDK to handle any errors or access token parsing.

    To get login success or failure callbacks, we implement a CallbackManager.Callback interface:

    private CallbackManager mCallbackManager;
    
    mCallbackManager = CallbackManager.Factory.create();
    
    // Login button callback registration
    mCallbackManager.registerCallback(callbackManagerCallback, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
          // App code for user logged in success
        }
    
        @Override
        public void onCancel() {
          // App code for login canceled
        }
    
        @Override
        public void onError(FacebookException exception) {
          // App code for login error
        }
    });
    

    This allows us to take app specific actions on login success, error or cancel events.

    That’s it! We have completed Facebook login integration in our Android app using Android Studio.

    Testing the integration

    It’s time to test our integration by running the app on a device or emulator.

    When you click the Facebook login button, it should open up the Facebook login screen.

    Enter your Facebook test user credentials and allow permissions. On successful login, the success callback we implemented should be triggered.

    Similarly test the cancel and error scenarios as well.

    Advanced: Get user profile data

    After a user logs in, you can get the user’s public profile information from Facebook:

    GraphRequest request = GraphRequest.newMeRequest(
      loginResult.getAccessToken(), 
      new GraphRequest.GraphJSONObjectCallback() {
        @Override
        public void onCompleted(JSONObject object, GraphResponse response) {
          String firstName = object.getString("first_name"); 
          String lastName = object.getString("last_name");
          String profilePicUrl = object.getString("profile_pic");
          String email = object.getString("email");
          
          // Use user data
        }
      });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "first_name,last_name,email,picture.type(large)");
    request.setParameters(parameters);
    request.executeAsync();
    

    We make a Graph API request to get user data and extract details like name, profile pic and email.

    This provides a seamless onboarding without any separate signup form.

    Conclusion

    Integrating Facebook login in Android app improves the signup flow for users. With just a few lines of code, you can implement Facebook login button and handle the callbacks.

    Some key things to remember:

    • Create Facebook app for Android platform
    • Add Facebook SDK dependency
    • Configure Facebook App ID
    • Add login button in layout
    • Handle login callbacks
    • Get user profile data after login

    With this guide, you should be able to seamlessly integrate Facebook login in your Android app using Android Studio.