Facebook Login in Android

Facebook Login in Android

Now a days almost every web and mobile app provides an option to Login with Facebook. This is because most of the people have a Facebook account and Facebook has provide an easy to integrate SDK to add Facebook Login to your mobile app.

Facebook SDK takes care of user’s privacy as well, When people log into your app with Facebook they can grant permissions to your app so you can retrieve information or perform actions on Facebook on their behalf. Most of the permissions require your review before granting it to the android app.

Facebook Login in Android

Facebook Login in Android provides a convenient and secure way for people to log in to an app without having to go through a sign-up process first. Using the latest version of Facebook’s SDK for Android, it takes only a few minutes to add this feature to your app.

In this quick tutorial, you will learn how to add a Facebook login button to an Android app and handle the events to log a user in using Facebook Login.

Before you begin, make sure you have access to the following:

Open your Android Studio, and create a New Project, or if you have some experience working with Android open your existing Project. I will be creating a new Project in this article and name it Facebook Login, and choose a Minimum API Level of 15, Android 4.0.3 (IceCreamSandwich) or higher and create your new project.

In your project, open your_app | Gradle Scripts | build.gradle (Project) and add the following repository to the buildscript { repositories {}} section to download the SDK from the Maven Central Repository:

In your project, open your_app | Gradle Scripts | build.gradle (Module: app) and add the following compile statement to the dependencies{} section to compile the latest version of the SDK:

Then build your project.

All apps that use the Facebook SDK must be registered with Facebook. Log in to the Facebook Developers website and click Add Product in the bottom left. (Register as a developer, if new). Select Facebook Login option.

Select the Android option and proceed. Go to option 3, Tell Us about Your Android Project option. Enter your package name and enter MainActivity as your default Activity. Save and proceed, you may get an error or rather a warning saying Facebook was unable to verify your package name in the Google Play Store, just click on Use this Package name.

Add Your Development and Release Key Hashes

To ensure the authenticity of the interactions between your app and Facebook, you need to supply us with the Android key hash for your development environment. If your app has already been published, you should add your release key hash too.

Generating a Development Key Hash

You’ll have a unique development key hash for each Android development environment. To generate a development key hash, on Mac, run the following command:


On Windows, run this command:

This command will generate a 28-character key hash unique to your development environment. Copy and paste it into the field below. You will need to provide a development key hash for the development environment of each person who works on your app.

Generating a Release Key Hash

Android apps must be digitally signed with a release key before you can upload them to the store. To generate a hash of your release key, run the following command on Mac or Windows substituting your release key alias and the path to your keystore:


This will generate a 28-character string, copy it and paste it in this section, in your Facebook Developer Page.

Edit Your Manifest File

Create strings for your Facebook app ID and to enable Chrome Custom Tabs, and add them along with the FacebookActivity to your Android manifest.

Open your /app/src/main/res/values/strings.xml file.

Add the following:

Open the /app/manifest/AndroidManifest.xml file.

Add a uses-permission element to the manifest:

Add the following meta-data element, an activity for Facebook, and an activity and intent filter for Chrome Custom Tabs after the application element. Replace @string/appname with the name of your Facebook App:

Create a new layout named main_activity.xml in res/layout. This is going to be a very simple layout with only three widgets:

  • LoginButton to allow the user to log in to Facebook
  • TextView to display the result of the latest login attempt
  • an ImageView to display the Image of the User’s Facebook Profile

You can place them inside a LinearLayout. After including attributes for padding and positioning the widgets, the layout’s XML will look something like this:

The SDK needs to be initialized before using any of its methods. You can do so by calling sdkInitializeand passing the application’s context to it. Add the following code to the onCreate method of your Activity:

Initialize your widgets, as shown below. Declare a CallbackManager as another field. The CallbackManager, as its name suggests, is used to manage the callbacks used in the app and initialize your instance of CallbackManager using the CallbackManager.Factory.create method.

It’s time to create a callback to handle the results of the login attempts and register it with the CallbackManager. Custom callbacks should implement FacebookCallback. The interface has methods to handle each possible outcome of a login attempt:

  • If the login attempt is successful, onSuccess is called.
  • If the user cancels the login attempt, onCancel is called.
  • If an error occurs, onError is called.

To register the custom callback, use the registerCallback method. The code to create and register the callback should look like this:

Tapping the login button starts off a new Activity, which returns a result. To receive and handle the result, override the onActivityResult method of your Activity and pass its parameters to the onActivityResult method of CallbackManager.


The final MainActivity should look like this:

Now, we need to extract the User’s info and show it, that is there Name and their Profile Image. We will add Glide, in our dependencies, to easily enable us load images. Add the following in your app’s build.gradle file:

Add the following to your repositories also, in the project level build.gradle file

Then hit sync gradle option. Lets now get our user’s info from Facebook and display it. We are going to use Facebook Graph API to get the User’s Data. Modify your login button code to look like this:

We then  create a loadUserData method, as shown below:

We are requesting the User’s information from Facebook using the Graph API here. The final code should look like this:

The above code only works after we sign in the first time. We are not storing the User Info in SharedPrefrences here, so if you navigate away from the app, the User data will be cleared on re-opening the app. You can save the data locally using either SharedPrefs or the amazing Android ORM’s available.

This is how the app will look like, when signing in

After successful sign in, the User data is displayed as shown below.

This was meant to show you the basics, you could try integrating the above code in your existing Android Apps to give your users an amazing experience when logging in to your applications. If you get any errors or get stuck, kindly leave a question below and I will be glad to help you out.

Important

Your app is now ready, but we need to make it live, switch from development mode. Open the ‘App Review‘ Tab : change

Do you want to make this app and all its live features available to the general public? Yes. Select the Education category in the drop down options.

And you app will be live now.

Conclusion

Your app is now complete. When you build it and deploy it on your Android device, you will see the Facebook login button. Tapping the login button takes you to a Facebook page that asks you to log in and authorize the app. After successfully logging in, the user’s profile will be displayed.

In this article, you learned how to use the Facebook SDK to add Facebook Login to your Android app. You also learned how to handle the possible outcomes of a login attempt. To learn more about Facebook Login, you can go through the reference for the Facebook SDK for Android.

Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *