Adding FB login into your Android app

Kulakshi Fernando
6 min readOct 4, 2020

--

Prerequisites

  • An FB account

A. Create an App in FB developer account

Please refer to my previous article for this part.

B. Integrating FB login in Android app — with java

(If you already have an app, please skip the first step)

Note: This article is written using Android Studio Version 4.0, for target Android version 30 and Java as the language

  1. Create a new app
  • Go to Android Studio
  • Go to File ->New Project -> Select Empty Activity (Or what you prefer) -> Click Next -> Give the project details -> Click Finish

2. Integrate FB Login to the Android app

Go to Facebook Login -> Quickstart
  • Select Android
Select Android from quickstart

(Now all the details you need are available on the page given by FB. I will anyway show all steps for the sake of completeness.)

  • (Download the Facebook SDK for Android — I believe that you can skip this step)
  • Add Facebook SDK in gradle.build files as told in the FB dev page. Following are my gradle.build files after newly creating the project and// adding FB SDK.
// build.gradle (Project)// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.0"

// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
google()
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}
// build.gradle (Module: app)apply plugin: 'com.android.application'

android {
compileSdkVersion 30
buildToolsVersion "30.0.0"

defaultConfig {
applicationId "com.example.fbloginandroid"
minSdkVersion 16
targetSdkVersion 30
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.facebook.android:facebook-android-sdk:[5,6)'
}
  • Go to the next step and add the package name and the default activity class name of your app.
add the package name and the default activity class name

When saving it you can select “Use this package name” if the project is not published.

Select “Use this package name” if the project is not published
  • You have to add the key hashes as mentioned in the machine that you are building the project. So go on and run the given codes in your command line. Then it will prompt to give a password. Type a password (and of course, remember it) and add the key hash you got in the dev account.

The following are the screenshots of my terminal. I created the release key hash also before I forget. You can do it later when you are going to release the app.

Note: In case you have created this kay hash before for any other app, make sure to insert the same key hash. You do not have to regenerate them for this app.

Dev key hash
Release key hash
Aet the key hash value/values in FB dev accout
  • Enable Single Sign On if you prefer and click Next.
  • Add the Facebook app ID, permission to use internet, and the activity for FB login as mentioned in the next step. Following is the code of my string.xml and AndroidManifest.xml after only updating with above changes after creating them.
<!--string.xml-->
<resources>
<string name="app_name">FBLoginAndroid</string>
<string name="facebook_app_id">1234436573585721</string>
<string name="fb_login_protocol_scheme">fb1234436573585721</string>
</resources>
<!--AndroidManifest.xml-->
<?
xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.fbloginandroid"
>
<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"
>

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<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>

</application>

</manifest>
  • I skipped both parts in the next step; event logging and adding purchase method, because I do not plan to use them.

Well, now all the configuration work is done, we can go ahead and add the login button.

  • Add the FB login button into the layout file (Here, I’m using the MainActivity itself).
<!--activity_main.xml-->

<?
xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>


<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="100dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
/>

</androidx.constraintlayout.widget.ConstraintLayout>

Ok, all done! Now if you run your project following screens should appear in the login process.

FB login in Android app

Note: In order to test FB login in developer mode, you have to add test users in FB dev account under your app (https://developers.facebook.com/docs/apps/test-users/).

C. Getting the required data from FB to be used in our app

Now that we can log in to FB, we should be able to get details of the user that we need to use in our app. So in this app, I expect to get a unique user id to identify the user, user name, user email, and user profile picture.

In order to get the user email and the profile picture, we need to get permission for it at the login. So add the login button in the onCreate() method of your activity and set permissions for login.

LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setPermissions(Arrays.asList("email","public_profile"));

Then register for callbacks that the app would receive in success or failure of the FB login process.

// Callback registration
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
// App code
Log.i("MAIN", "FB login Success");
}

@Override
public void onCancel() {
// App code
Log.i("MAIN", "FB Login Canceled");
}

@Override
public void onError(FacebookException exception) {
// App code

Log.i("MAIN", "FB Login Error ");
Log.i("MAIN", exception.toString());
}
});

Now, you can use either onSuccess() method of the above callback, or the onActivityResult to get data after logging in.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
callbackManager.onActivityResult(requestCode, resultCode, data);
super.onActivityResult(requestCode, resultCode, data);

final AccessToken accessToken = AccessToken.getCurrentAccessToken();
boolean isLoggedIn = accessToken != null && !accessToken.isExpired();


if(isLoggedIn) {
GraphRequest request = GraphRequest.newGraphPathRequest(
accessToken,
"/me",
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
// Insert your code here
JSONObject user = response.getJSONObject();
try {
String id = user.getString("id");
String name = user.getString("name");

Log.i("MAIN", "FB User Details:");
Log.i("MAIN", "User ID: " + id);
Log.i("MAIN", "Name: " + name);

GraphRequest request_email = GraphRequest.newGraphPathRequest(
accessToken,
"/me?fields=email",
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
// Insert your code here
Log.i("MAIN", "Email: " + response.toString());
}
});
request_email.executeAsync();

GraphRequest request_picture = GraphRequest.newGraphPathRequest(
accessToken,
"me?fields=picture",
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
// Insert your code here
Log.i("MAIN", "Profile pic details: " + response.toString());
}
});
request_picture.executeAsync();

} catch (JSONException e) {
e.printStackTrace();
}
}
});

request.executeAsync();
}

}

--

--