In this Tutorial I am going to discuss about How to integrate facebook login to android app .

Today social login is the best way to authenticate a user rather than forcing users to create a profile or account, remember a new password and fill-in all the required details, you can just point them to the login screen to select their social channel to authentication. It provide a happy path for both the users and developers .

1. Login to facebook :

At first we have to log in to Facebook to create apps or register as a developer. Facebook Login

2. Create a New App Id :

After Login to facebook as developer, We need to create an App Id to integrate facebook login button to our Android app.
Now go to My Apps and Create or Add New App . Add an App Name to Display and
contact email then submit it. Now you will get your App ID, Copy it some where.

3. Add Platform :

After creating App Id, Go to settings->Basic and add Platform(In bottm of the page) i.e. Android and save the changes.

4. Add Your Development and Release Key Hashes to settings->Basic platform details :

After Adding your selected platform now generate your hashkey .

Generate Development Keyhash :
To generate a development key hash, open a terminal window and run the following command.

Window Development KeyHash :

keytool -exportcert -alias androiddebugkey -keystore
“C:\Users\USERNAME.android\debug.keystore” |
“PATH_TO_OPENSSL_LIBRARY\bin\openssl” sha1 -binary |
“PATH_TO_OPENSSL_LIBRARY\bin\openssl” base64

Mac Os Development Keyhash :

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

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

keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore
YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64

After generating keyhash add this to your platform details.

5. Create a New Project :

Lets we start with a new project in Android Studio from File New Project ⇒
select Empty Activity and go through it.

6. Implement the facebook SDK :

To use the Facebook SDK in a project, add it as a build dependency and import
the Facebook SDK packages. We have to Import Facebook sdk in our app’s project-level build.gradle file and add the following implementation statement to the dependencies{} section. Try to add the latest version of the Facebook SDK. Once that’s done, save the file and perform a Gradle sync.

implementation 'com.facebook.android:facebook-android-sdk:[4,5)'

7. Edit your AndroidManifest.xml :

After this Open the /app/manifest/AndroidManifest.xml file add the Internet
Permission to access your mobile’s Internet.

<uses-permission android:name="android.permission.INTERNET"/> 

Also add the following meta-data element, an activity for Facebook inside your application element:

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

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 package="com.technxtcodelabs.facebook_login">
 <uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.VIBRATE"/>
 <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=".LoginActivity">
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>
 <activity android:name=".DashboardActivity" />
 </application>
</manifest>

8. Create strings for your Facebook app ID :

Open your /app/res/values/strings.xml file and add the following line of code :

<string name="facebook_app_id">[APP_ID]</string>
<string name="fb_login_protocol_scheme">fb[APP_ID]</string>

9. Implement the Facebook Login Button to your Layout resource file :

Create a Button to your XML Layout file i.e. activity_main.xml to display it for better user experience. The simplest way to add Facebook Login to your app is to add LoginButton from the SDK. 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. The button
follows the login state, and displays the correct text based on someone’s
authentication state.
Add the Facebook Login button to your layout XML file:

<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="30dp"
 android:layout_marginBottom="30dp" />

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".LoginActivity">
 <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="30dp"
 android:layout_marginBottom="30dp" />
</RelativeLayout>

10. Implement Facebook Login service to your LoginActivity.java :

Now Add the following code to implement facebook button to your project in LoginActivity.java file.

package com.technxtcodelabs.facebook_login;

import android.support.v4.content.ContextCompat;
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.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class LoginActivity extends AppCompatActivity implements
View.OnClickListener{
 private static final int REQ_CODE = 9001;
 private CallbackManager callbackManager;
 private LoginButton fblogin;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_login);
 FacebookSdk.sdkInitialize(getApplicationContext());
 callbackManager = CallbackManager.Factory.create();
 fblogin =(LoginButton) findViewById(R.id.login_button);
 btnlogin.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
 login();
 }
 });
 login_button.setOnClickListener(this);
 }
 @Override
 public void onClick(View v) {
 switch (v.getId()){
 case R.id.login_button:
 facebooklogin();
 break;
 }
 }

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

 }
 @Override
 public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
 Log.d( "onConnectionFailed:" ,connectionResult.toString());
 }
 public void facebooklogin(){
 callbackManager = CallbackManager.Factory.create();
 login_button.setReadPermissions(Arrays.asList("public_profile",
"email"));

login_button.registerCallback(callbackManager, new
FacebookCallback<LoginResult>() {
 @Override
 public void onSuccess(LoginResult loginResult) {
 Log.d("Success Result",loginResult.toString());
 String accessToken = loginResult.getAccessToken()
 .getToken();
 Log.i("accessToken", accessToken);
 GraphRequest request = GraphRequest.newMeRequest(
 loginResult.getAccessToken(), new
GraphRequest.GraphJSONObjectCallback() {
 @Override
 public void onCompleted(JSONObject json,
GraphResponse response) {
Log.d("FacebookResponce",json.toString());
 Log.d("Graph Response: ",response.toString());
 try {
 Log.d("Id :",json.getString("id").tostring());
 try {
 URL profile_pic = new URL(
 "http://graph.facebook.com/" +
id + "/picture?type=large");
 Log.i("profile_pic",
 profile_pic + "");
 } catch (MalformedURLException e) {
 e.printStackTrace();
 }
Log.d("Name :",json.getString("name").toString());
Log.d("Email :",json.getString("email").toString());
 Log.d("UserDate", String.valueOf(json));

// Intent intent = new
Intent(LoginActivity.this,DashboardActivity.class);
// startActivity(intent);
// finish();
 } catch (JSONException e) {
 e.printStackTrace();
 };
 }
 });
 Bundle parameters = new Bundle();
 parameters.putString("fields", "id,name,email,gender");
 request.setParameters(parameters);
 request.executeAsync();
 }
 @Override
 public void onCancel() {
System.out.println("onCancel");
 Log.e("Cancel","Canceled");
 }

@Override
 public void onError(FacebookException error) {
 Log.e("Error",error.toString());
System.out.println("onError");
 Log.v("LoginActivity", error.getCause().toString());
 }
 });
 }
}

11. Create an another Activity and select Empty Activity :

Now we create an another activity named as DashboardActivity to get the final result.

12. Implement a TextView to your layout resource of second activity :

Now we implement a TextView to show that Login is successfull in your activity_dashboard.xml file.

activity_dashboard.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="5dp"
 android:paddingLeft="5dp"
 android:paddingRight="5dp"
 android:paddingTop="5dp"
 tools:context=".DashboardActivity">
 <TextView
 android:id="@+id/success"
 android:layout_width="wrap_content"
 android:textStyle="bold"
android:text="Login Successful"
android:layout_centerVertical="true"
 android:layout_centerHorizontal="true"
 android:layout_height="wrap_content" />

</RelativeLayout>

13. Show the successfull login to Second Activity :

Now Add the following code to your project to successfull geting the result in DashboardActivity.java file.

DashboardActivity.java

package com.technxtcodelabs.facebook_login;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;

public class DashboardActivity extends AppCompatActivity {
 TextView success;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 success = (TextView) findViewById(R.id.success);
textViewAmount.setText("Login Successfull.");
 }
}

14. LogOut :

To create a logout button just add this line to click listener of your logout button and clear your user sharedpreference.

LoginManager.getInstance().logOut();

Now run the project/app in android device or any Emulator .

%d bloggers like this: