How to implement Facebook Login in Android Studio?

In our few earlier posts, we wrote a tutorial on how to add Google Login to your Android App. In this tutorial i would be teaching you, how you can implement Facebook Login for your Android App.

Note: The next two content section is taken from official Facebook Developers Site.

Why you should use Facebook Login in your android app?

According to Facebook, they have given this feature to full fill these three usecases

  • Account Creation
    Facebook Login lets people quickly and easily create an account in your app without having to set (and likely later forget) a password.
    android latest version This simple and convenient experience leads to higher conversion. Once someone has created an account on one platform, they can log into your app—often with a single click—on all your other platforms. A validated email address means you’re able to reach that person to re-engage them at a later date.
  • Personalization
    Personalized experiences are more engaging and lead to higher retention. Facebook Login lets you access information which would be complex or arduous to collect via your own registration form. Even just importing someone’s profile picture imported from Facebook gives them a stronger sense of connection with your app.
  • Social
    Many highly retentive apps let people connect with their friends in order to enable shared in-app experiences. Facebook Login lets you know which of your app’s users are also friends on Facebook so you can build value by connecting people together.

Advantages of using Facebook Login in your Android App

  • Real Identity
    When people choose to log in with Facebook, they can share their real identity through their public profile. Public Profile includes a person’s real name and a profile picture. Apps based on real identity often have less spam and foster higher quality conversations.
  • Cross Platform Login
    Facebook Login is available on the most common mobile and desktop app platforms. People who create accounts with Facebook on one platform can quickly and easily log into your app on another. A person is known by the same User ID everywhere so they can pickup your in-app experience where they left off.
  • Works Alongside Your Existing Account System
    Facebook Login complements your existing account system. Give people the option to log in with Facebook alongside email, SMS or other social login choices. Where an email address you get from Facebook Login matches one already in your system, you can log that person into their existing account without additional passwords.
  • Granular Permissions
    Facebook Login supports many permissions which determine which information people choose to share with your app. This means you have precise control over what you request and people have precise control over what they choose to approve.
  • People Have Control Over What They Share
    Great experiences start by giving people control. With Facebook Login, people can choose which information they share with your app. They can still get the benefits of logging in with Facebook even if they feel uncomfortable granting access to certain information. Your app can later re-request this information once you’ve explained how the person’s experience will be enhanced.
  • Gradual Authorization
    Facebook Login supports the gradual authorization—you don’t have to request all the information you want up front—you can do it over time. This means people can quickly and easily create accounts in your app—and as their experience with your app deepens, you can request addition information to further enhance their experience.
  • Facebook Lite Integration for Android Apps
    When you develop your app with version 4.14.0 of the Facebook SDK for Android, Facebook Login has automatic integration with Facebook Lite. If people don’t have the Facebook Android app installed, Facebook Login uses Facebook Lite instead to display the login screen and get credentials. Previous SDKs required that people have the Facebook app installed.

Steps to implement Facebook Login functionality

  1. Create a New Android Studio Project by going to File menu.
  2. Name the Project, give a unique package name and then click next
  3. Select Minimum SDK as API 15 : Android 4.0.3 (Ice Cream Sandwich) or higher. This is required for Facebook SDK to function correctly.
  4. Choose the activity type as Empty Activity and click next.
  5. Name the activity. Make sure Generate Layout File check box is selected.
  6. In /app/build.gradle  add this
    repositories {
      mavenCentral()
    }

     

  7. As you would be using Facebook SDK, add the compile dependency in build.gradle file
    dependencies {
      compile 'com.facebook.android:facebook-android-sdk:4.+'
    }

     

  8. Build your project.
  9. Import FacebookSDK into your Android application
  10. Now you need to create FacebookApp ID

How to create Facebook App ID?

  1. Logon to https://developers.facebook.com/. Simply register as a developer.
  2. Go to My Apps
  3. Then click add a new app.
  4. Type you app name in Display Name and choose a category.
  5. Then click Create App Id button.
  6. From the left click on Settings menu.
  7. Click on add a platform and select Android.
  8. Now enter your package name and class name of your main activity and click on save changes.NEWBIE TIP:- You can find package name in your Android Manifest.
  9. To generate a key hash then add a temporary code to the onCreate() of MainActivity class.
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Add code to print out the key hash
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "org.snowcorp.facebooklogin",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
        } catch (PackageManager.NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
    ...

     

  10. Save the changes that you have made and run the app.
  11. Check your logcat output for a message.
  12. Copy the keyhash and enter that to your app settings in facebook and click save.

Integrating the App ID in your Android Studio Project

  1. Open your strings.xml file.
  2. Add a new string with the name facebook_app_id containing the value of your Facebook App ID:
    <string name="facebook_app_id">YOUR APP ID</string>

     

  3. Open AndroidManifest xml file.
  4. Add below line in hte manifest file
    <uses-permission android:name="android.permission.INTERNET"/>

     

  5. Add a meta-data element to the application element:

    <application
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
        ....
        <meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id"/>
        ....
    </application>

     

  6. Add the FacebookActivity also in the manifest file
    <activity android:name="com.facebook.FacebookActivity"
              android:configChanges=
                     "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
              android:label="@string/app_name" />

     

  7. (OPTIONAL)Enable Chrome Custom Tabs by adding an intent filter to your manifest and a fb_login_protocol_scheme to your strings.xml file.

    <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>

     

  8. Add below code in strings.xml
    <string name="fb_login_protocol_scheme">fbYOUR_APP_ID</string>

     

  9. Now to add the Facebook Login Button , add the follwing code to the xml layout
    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true" />

     

  10. Now you have to set up the button in your UI by adding it to a fragment and update your activity to use your fragment.
  11. To to pass the login results to the LoginManager via callbackManager
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

     

  12. Add a ImageView in your layout for user’s profile picture.
    <ImageView
        android:id="@+id/user_pic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:background="@drawable/border" />

    This code above would display the Profile picture of the intended Facebook user.

  13. To display User info such as username and email address, add the below code:
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="25sp"/>
    <TextView
        android:id="@+id/email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:textSize="17sp" />

     

  14. Go to MainActivity.java
  15. Inside the onSuccess() method insert this code.
    GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    Log.e("response: ", response + "");
                    try {
                        String KEY_UID = object.getString("id");
                        String KEY_EMAIL = object.getString("email");
                        String KEY_FIRSTNAME = object.getString("first_name");
                        String KEY_LASTNAME = object.getString("last_name");
                        String KEY_PROFILE_PIC = "https://graph.facebook.com/" + KEY_UID + "/picture?type=large";
                        userName.setText(KEY_FIRSTNAME + " " + KEY_LASTNAME);
                        userEmail.setText(KEY_EMAIL);
                        Glide.with(getApplicationContext())
                                .load(KEY_PROFILE_PIC)
                                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                                .centerCrop()
                                .transform(new CircleTransform(getApplicationContext()))
                                .into(userPic);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id, first_name, last_name, email");
    request.setParameters(parameters);
    request.executeAsync();

    NOTE:- Add Glide library to your project add below code to build.gradle

    compile 'com.github.bumptech.glide:glide:3.7.0'

     

  16. Save the changes.
  17. Sync the project.
  18. Run the App.

Final Note from Editor

Thus now you can use Facebook Login feature on your newly made app.If you find any difficulty in above tutorial, comment below down on this post and one of the androidhire staff would be helping you out.

Related Stories