The Facebook SDK for Android enables people to sign into your app with Facebook Login. 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.
To integrate Facebook login first, we need to register our application in the Facebook developer site to allow Facebook to authenticate all API requests that are coming from our app, for that open Facebook Developer site and follow the below steps to create an App ID for your android application.
Once we open Facebook developer site, click on Create a New App button to create an App Id for our android application like as shown below.
Once we click on Create a New App, a new popup window will open in that enter display name of our app, contact email and click on Create App ID like as shown below.
Once we enter all the details and click on Create App ID, it will open the Security check window with captcha, enter the captcha and click on submit like as shown below.
Once we are done with creation of App, our App ID will be shown as shown below.
Now we will add Facebook SDK to our android application, for that create a new android application using android studio and give names as FacebookLoginExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
To add Facebook SDK in your project, make it a dependency in Maven or download it. Choose the method which you preferred like as shown below.
In case if you select Maven to use Facebook SDK, we need to add the build dependency in our project, for that open your app à Gradle Scripts à build.gradle (project) and add mavenCentral() repository to the buildscript {repositories{}} section to download the SDK from the Maven Central Repository as shown below.
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
Now we need to add Facebook compile statements to our application, for that open your app à Gradle Scripts à build.gradle (Module: app) and add following compile statement to the dependencies{} section to compile the latest version of Facebook Login SDK.
dependencies {
...
compile 'com.facebook.android:facebook-login:[4,5)'
...
}
Once you are done with adding required dependencies, build your application to update with required SDK’s.
Now add Android Application Package Name and Default Activity Class name on Facebook, then click on save button like as shown below.
After click on Save button, a Popup will display, in that click on Use this Package Name button like as shown below.
To ensure the authenticity between our app and Facebook, we need to add Android key hash for our development environment. In case, if your app has already been published, you need to add both Android key hash and release key hash for your development.
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 in terminal.
On Windows, run this command in terminal.
This command will generate a 28-character key hash unique to your development environment. Copy and paste it into the Key Hashes input field below. You will need to provide a development key hash for the development environment of each person who works on your app.
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.
We need to enable a Single Sign-On for our app, for that select Yes and click Save like as shown below.
Now we will add our Facebook App ID in strings.xml file, for that open strings.xml file from /res/values path and following string values.
<string name="facebook_app_id">297800690726297</string>
<string name="fb_login_protocol_scheme">fb297800690726297</string>
We need to add following details in our manifest file (AndroidManifest.xml) to set required user permissions, meta data and activity details.
We need to add Internet permission in our manifest file, for that open AndroidManifest.xml file from /app/manifests/ path.
Add the following meta-data element to application element in AndroidManifest.xml file.
<application ...>
...
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="@string/facebook_app_id"/>
...
</application>
Add following facebook activity in android manifest file.
We need to add the following activity and intent filters for Chrome Custom Tabs to allow a Facebook SDK to provide a login dialog instead of Webview, in case if Facebook app is not installed. As a result, people do not have to enter their credentials, if they already logged into Facebook in their Chrome browser.
<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>
Once we add all the required elements our AndroidManifest.xml file should contain the code like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.facebookloginexample">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<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>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
By using Facebook SDK we can add LoginButton to our application. The LoginButton is a UI element that wraps functionality available in the LoginManager. When someone clicks on the button, the login is initiated with the permissions set in the LoginManager.
In our activity_main.xml layout file, we need to add Facebook Login button using full class name com.facebook.widget.LoginButton like as shown below.
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="150dp"
android:layout_marginBottom="30dp" />
The complete code of our activity_main.xml file will be like as shown below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical" >
<com.facebook.login.widget.LoginButton
android:id="@+id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="150dp"
android:layout_marginBottom="30dp" />
</LinearLayout>
Now we need to add the following code details in MainActivity.java file to set callback manager, read permissions, etc. to use facebook login in our applications.
By using CallBackManager.Factory.create we can create a callback manager to handle login responses and we need to set read permissions using setReadPermissions() method to get user details from Facebook.
Following is the code to add callback manager and setting read permissions to read user details from a Facebook profile in the activity file.
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
}
}
To respond to a login result, we need to register a callback with either LoginManager or LoginButton. In case, if we register the callback with LoginButton, we don't need to register the callback on Login manager.
We need to add the callback to our activity or fragment's onCreate() method like as shown below.
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
}
}
The onActivityResult() forward the login results to the callbackManager created in onCreate() method.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
The complete code of our MainActivity.java file will be like as shown below.
package com.tutlane.facebookloginexample;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
public class MainActivity extends AppCompatActivity {
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();
LoginButton loginButton = (LoginButton)findViewById(R.id.login_button);
loginButton.setReadPermissions("email");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
}
@Override
public void onCancel() {
// App code
}
@Override
public void onError(FacebookException exception) {
// App code
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
When we run above program in android studio we will get the result like as shown below.
When we click on Continue with Facebook button, it will show popup to login with Facebook, once you logged in successfully we will get the logout button like as shown below.
This is how we can integrate Facebook login in android applications based on our requirements.