---
title: "Steps for Facebook Login in android."  
description: "Steps for Facebook Login in android."  
author: "Arti Mishra"  
published: 2018-09-20  
updated: 2018-10-09  
canonical: https://www.mindstick.com/forum/34678/steps-for-facebook-login-in-android  
category: "android apps"  
tags: ["android", "facebook graph api", "facebook login"]  
reading_time: 7 minutes  

---

# Steps for Facebook Login in android.

Step by step [guide](https://www.mindstick.com/articles/44463/business-to-business-vat-reclaiming-a-guide-for-your-employees) for [Facebook Login](https://www.mindstick.com/forum/34671/android-facebook-login-api-returns-only-name-and-id) in android.

## Replies

### Reply by Sahil Arora

Post is removed by the Admin.

### Reply by Arti Mishra

For [Facebook](https://www.mindstick.com/articles/44467/successful-companies-that-utilize-facebook-as-a-social-media-platform) [login](https://www.mindstick.com/articles/12852/styles-login-form-in-android) in android, first of all, register your app.\

## Registering Your Facebook App

**Step 1:** First you log in using your Facebook account to **https://developers.facebook.com/apps/.**

![Steps for Facebook Login in android.](https://www.mindstick.com/mindstickforums/916f8f2b-1ba6-41ca-996f-2fa03cc99fd5/images/11d09346-d993-4599-a58b-9c515fff45f5.png)

**Step 2**: Click on **create a new app**. And **set the app name and the email id** as shown in the below pic.

![Steps for Facebook Login in android.](https://www.mindstick.com/mindstickforums/916f8f2b-1ba6-41ca-996f-2fa03cc99fd5/images/a24bf0df-da64-4e74-9776-bd663f525202.png)

**Step 3:** You shall see the dashboard in the next screen. Choose Facebook Login Setup and **select the platform as Android** as shown in the below images.

![Steps for Facebook Login in android.](https://www.mindstick.com/mindstickforums/916f8f2b-1ba6-41ca-996f-2fa03cc99fd5/images/ae94b257-faaa-4e14-a909-6528ef4b25c7.png)

**Step 4:** After that, **add the following dependencies in your app‘s build.gradle.**

```
buildscript {  repositories {
mavenCentral()
}
}  
```

**Step 5:** Use the **latest version of the SDK dependency.**

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

**Step 6:** To check the SDK is successfully added in our project add the following import statements in your **MainActivity.java** class file as shown below. **If there’s no error, the build was successful.**

```
import com.facebook.FacebookSdk; import com.facebook.appevents.AppEventsLogger;
```

**Step 7:** Add your Facebook App ID inthe **string.xml** file.

```
<string name="facebook_app_id">2048405422006344</string>
<string name="fb_login_protocol_scheme">fb2048405422006344</string>
```

**Step 8:** Enter your **package name** and **default activity name with the fully qualified path** as shown below. After saving click on Use this package name to confirm.

![Steps for Facebook Login in android.](https://www.mindstick.com/mindstickforums/916f8f2b-1ba6-41ca-996f-2fa03cc99fd5/images/2e5de32e-35bb-4a67-9bb2-110d215c81a0.png)

**Step 9:** The next window asks for the **add key hashes**. That can be done by **running the following commands on windows cmd.**

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

**You will need the following steps for generating a hash key.**

1. Download OpenSSL library for Windows from the **https://code.google.com/archive/p/openssl-for-windows/downloads.**

2. Open your java bin path location and copy it. And after that open cmd and write some command .

Cd C:\Program Files\Java\jdk-9.0.4\bin (click enter)

Write some key tool command-

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\msclient009\.android\debug.keystore" | "C:\openssl-0.9.8e_X64\bin\openssl" sha1 -binary | "C:\openssl-0.9.8e_X64\bin\openssl" base64

**Above command will generate a 28-character key hash unique to your development environment.** And after that **add key hashes in your Facebook page.**

**Step 10:** Add internet permissions in the **AndroidManifest.xml** file by adding the following line in the **manifest file.**

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

**Step 11:** Add Following **meta-data tag** **in your AndroidManifest.xml file.**

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

**Step 12:** Add some code in your **activity_main.xml file**

```
<FrameLayout
    android:id="@+id/FrameLayout1"
    android:layout_width="match_parent"
    android:layout_height="@dimen/button_height"
    android:layout_below="@+id/sign_in_button"
    android:layout_marginTop="@dimen/card"
    android:layout_weight="1"
    android:background="@drawable/login_button"
    android:elevation="3dp">    <com.facebook.login.widget.LoginButton        android:id="@+id/fb_login_button"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_marginTop="@dimen/bottom"        android:background="#4285F4"        android:textSize="@dimen/text_size" />    <Button        android:id="@+id/fb"        android:layout_width="match_parent"        android:layout_height="50dp"        android:background="#4285F4"        android:drawableStart="@drawable/fb_icon"        android:padding="@dimen/bottom"        android:text="@string/com_facebook"        android:textColor="@color/back"        android:textSize="@dimen/text_size" /></FrameLayout>
```

**MainActivity.java file**\

```
loginButton = (LoginButton) findViewById(R.id.fb_login_button);FacebookSdk.sdkInitialize(getApplicationContext());AppEventsLogger.activateApp(this);callbackManager = CallbackManager.Factory.create(); // create instance of callback manager classif (Utils.isNetworkAvailable(getApplicationContext())) {   loginButton.setReadPermissions(Arrays.asList(EMAIL, PUBLIC_PROFILE));    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {        @Override        public void onSuccess(LoginResult loginResult) {          accessTokenFacebook = loginResult.getAccessToken();            final GraphRequest request = GraphRequest.newMeRequest(accessTokenFacebook, new GraphRequest.GraphJSONObjectCallback() {                @Override                public void onCompleted(JSONObject object, GraphResponse response) {                    Log.i("GraphResponse", response.toString());                    Log.i("JSONObject", object.toString());                    // Get facebook data from login                    String email="";                    try {                       String userName = object.getString("name");                       String id = object.getString("id");                       email=object.getString("email");                        String firstName = " ", lastName = " ";                        if (userName != null) {                            int end = userName.lastIndexOf(' ');                            if (end >= 0) {                                firstName = userName.substring(0, end);                                lastName = userName.substring(end + 1, userName.length());                            }                        }                        Toast.makeText(getApplicationContext(),"Facebook Login Successful",Toast.LENGTH_SHORT).show();                        if(email.equals("")) {Toast.makeText(getApplicationContext(),getResources().getString(R.string.email_permission),Toast.LENGTH_SHORT).show();                        }                        else {                            loginApi("facebook", id, firstName, lastName, email);                        }                    } catch (Exception e) {                        e.printStackTrace();                    }                }            });            Bundle parameters = new Bundle();            parameters.putString("fields", "id,name,email"); // Add some field as per user requirement            request.setParameters(parameters);            request.executeAsync();        }        @Override        public void onCancel() {            Log.d("facebook Login","On cancel");        }        @Override        public void onError(FacebookException error) {            Log.v("Error", error.toString());        }    });} else {    Toast.makeText(this, getResources().getString(R.string.no_internet), Toast.LENGTH_SHORT).show();}// Login Api AsyncTask Codepublic void loginApi(String provider, String providerId, String firstName, String lastName, String emailId) {    LoginAsyncTask asyncTask = new LoginAsyncTask(getApplicationContext(), provider, providerId, firstName, lastName, emailId);    asyncTask.delegate = this;    asyncTask.execute();}@Overridepublic void onActivityResult(int requestCode, int resultCode, Intent data) {    super.onActivityResult(requestCode, resultCode, data);    Log.v("Request Code", String.valueOf(requestCode));    if (requestCode == REQ_CODE_GOOGLE_SIGN_IN) {        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);        handleSignInResult(task);    }   if(requestCode == REQ_CODE_FB_SIGN_IN){       callbackManager.onActivityResult(requestCode, resultCode, data);    }}
```


---

Original Source: https://www.mindstick.com/forum/34678/steps-for-facebook-login-in-android

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
