Facebook Login for Android: A Step-by-Step Guide

With over 2400 million users, integrating Facebook login into your Android app makes sense for a quicker and improved user experience.

Users also developed a severe case of impatience. They expect it to be instantaneous, whether it's watching a video on YouTube or downloading an app.

Facebook Login for Android

Let's get started because I don't want to waste your time.

In this tutorial, you’re about to produce an easy login system with Facebook.

We additionally wrote a tutorial on mechanical man Facebook Login with base of operations AUTH that was exhausted mechanical man Studio.

This tutorial is while not mechanical man Studio. Cool?

1. Choose Associate App or Produce a Replacement App

First of all, head to the Facebook Developer Console. choose associate older app if you've got or produce a replacement app.

Now a popup box seems Enter show Name, Contact Email and build a replacement app Id.

Then Facebook may well be asking you to fill the captcha. simply fill and hit Enter.

Now you'll be able to see the app is generated.

2. transfer the Facebook App

Now if you don’t have Facebook put in on your device. simply install it from Google Play Store.

By the way, downloading the app isn't necessary.

But if you didn’t transfer the app. it'll send to the browser.

3. Create/Open a Project

Now open associate degree existing project or produce a replacement mechanical man Studio Project

4. Integrate the Facebook SDK

The Facebook login SDK is part of the Facebook SDK For Android. To incorporate Login SDK into your application. A maven repository must be included.
  • Simply go to the app -> Gradle Scripts -> create to get started. Gradle(project) and paste the code below into buildScript repositories; then sync Now.
//paste code inside buildScript { repositories {} };
jcenter()
  • Now go to Gradle Scripts -> Create in the app. Gradle(app) and paste the code below into the dependencies block, then hit Sync Now.
//paste inside 
implementation 'com.facebook.android:facebook-login:[5,6)'

5. In the strings.xml file, add the files you want to use

Add the following code to the resources> Tag in your app/res/values/strings.xml file.

//Add below code inside like <resources> TAG
  
// syntx
<string name="facebook_app_id">[place your key here]</string>
<string name="fb_login_protocol_scheme">[place your protocol key here]</string>
  
//For Example 
<string name="facebook_app_id">449671255559432</string
<string name="fb_login_protocol_scheme">fb449671255559432</string>
 
//The Facebook developer console is where you'll find your key.

In section 4 of the Facebook developer console, you can find your app key and protocol key.

6. In AndroidManifest.xml, add the files you want to use

Add the following code to the manifest> TAG in the app/manifests/AndroidManifest.xml format.

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

Now paste below metadata element, Facebook activity, customTabActivity inside <application> TAG

//Must place this code inside <application> TAG
<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>

7. Link Your App to Your Package Name and Default Class

Now go to Facebook's developer console and scroll down to part 5. Now type in the package name and the default operation class name (this is the class that handles your login functionality) and hit save.

8. Provide the app's creation and release key hashes

You'll need two items in order to produce a release key.

1. The Java Development Kit's key and certificate management tool (key tool).
2. In the cmd terminal, open SSL for the window (you can get it from Google code archive) and paste the following code.

//This is a Syntx      
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
      
//This is a Example
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Arslan\.android\debug.keystore" | "D:\openssl-0.9.8k_X64\bin\openssl" sha1 -binary | "D:\openssl-0.9.8k_X64\bin\openssl" base64

9. Add a Facebook Login Button to your page

Now, inside activity_main.xml, add the following code.

<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:text="Login here with Facebook"
        android:layout_marginTop="30dp"
        android:layout_marginBottom="30dp" />

10. In MainActivity.java, write some code

First and foremost, declare these fields in the MainActivity class.

//Put these in the beginning of the MainActivity class
    CallbackManager callbackManager;
    LoginButton loginButton;

Make a callback method solely for handling login responses. Simply copy and paste the code below into the MainActivity onCreate() process.

//This should be pasted into the oncreate method.
callbackManager = CallbackManager.Factory.create();

Now register a recall methodology in your onCreate() methodology. If you're adding a button within the fragment then you've got to update your activity to use the fragment. you'll place these properties within the onCreateView() if you're employing a fragment. After registering the recall methodology you'll get all the profile info exploitation GraphRequest. this may provides you a JSON format info of the logged within the user. Then you'll filter this info and use this within your app.

//Inside the Create process declare
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends","user_gender"));

//Call loginButton.setFragment(this) if you're using it in a fragment.  

loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
public void onSuccess(LoginResult loginResult) {
                Log.e("TAG","login");
//To get the data into the app, use GraphApi.
GraphRequest request = GraphRequest.newMeRequest(
                //pass two parameter
                loginResult.getAccessToken(), //one is the current token
                new GraphRequest.GraphJSONObjectCallback()  //2nd is grahJSONObject callback
                {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.v("MainActivity", response.toString());

                        //Application code
                        try {
                            String obj = object.toString();  //Get a complete list of JSON objects.
                            String name = object.getString("name");   //Obtain a specific JSON Object
                            String email = object.getString("email");
                            String birthday = object.getString("birthday"); //01/30/1980 format
                            String id = object.getString("id");
                            String gender = object.getString("gender");
                            String profileURL = "";
                            if (Profile.getCurrentProfile() != null) {  
//Since some people don't have a profile photo, check this box.
                                profileURL = ImageRequest.getProfilePictureUri(Profile.getCurrentProfile().getId(), 400, 400).toString();
//Using Glide or the retrofit library, you can easily set the profile URL to image view.
                            }

                            Log.v("completeObjInfo",obj);
                            Log.v("TAGObjectInfo","id: "+id);
                            Log.v("TAGObjectInfo","name: "+name);
                            Log.v("TAGObjectInfo","email: "+email);
                            Log.v("TAGObjectInfo","birthday: "+birthday);
                            Log.v("TAGObjectInfo","gender: "+gender);
                            Log.v("TAGObjectInfo","profileURL: "+profileURL);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,email,gender,birthday");                   
        //Set these parameter
        request.setParameters(parameters);
        request.executeAsync();                                 
        //Exuecute task in seprate thread

    }

    @Override
    public void onCancel() {
        //App code
        Log.v("MainActivity", "cancel");
    }

    @Override
    public void onError(FacebookException exception) {
        //App code
        Log.v("MainActivity", exception.getCause().toString());
    }
});

If the login button works properly, the LoginResult parameter contains a new accessToken as well as the most recent permission that has been granted or refused.

Finally, clearly decision callbackManager in your onActivityResult() technique. LoginManager receives the login results via onActivityResult().

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

Here is the complete code of MainActivity.java

package com.example.demodemo;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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.Profile;
import com.facebook.ProfileTracker;
import com.facebook.internal.ImageRequest;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.firebase.analytics.FirebaseAnalytics;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;


public class MainActivity extends AppCompatActivity {
    CallbackManager callbackManager;
    LoginButton loginButton;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FacebookSdk.sdkInitialize(this.getApplicationContext());
        setContentView(R.layout.activity_main);

        callbackManager = CallbackManager.Factory.create();
        loginButton = (LoginButton) findViewById(R.id.login_button);

        //When the button is pressed, these parameters are added to the Array as a list.
        loginButton.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends","user_gender"));
        //If you are using in a fragment, call loginButton.setFragment(this);
        //Callback registration
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.e("TAG","login");
                //Use GraphApi to get the information into the app.
                GraphRequest request = GraphRequest.newMeRequest(
                        //pass two parameter
                        loginResult.getAccessToken(),                       
//one is the current token
                        new GraphRequest.GraphJSONObjectCallback()          
//2nd is grahJSONObject callback
                        {
                            @Override
                            public void onCompleted(JSONObject object, GraphResponse response) {
                                Log.v("MainActivity", response.toString());
                                //Application code
                                try {
                                    String obj = object.toString(); //get complete JSON object refrence.
                                    String name = object.getString("name");                 
//get particular JSON Object
                                    String email = object.getString("email");
                                    String birthday = object.getString("birthday"); 
// 01/31/1980 format
                                    String id = object.getString("id");
                                    String gender = object.getString("gender");
                                    String profileURL = "";
                                    if (Profile.getCurrentProfile() != null) {                  
//Since some people don't have a profile photo, check this box.
                                        profileURL = ImageRequest.getProfilePictureUri(Profile.getCurrentProfile().getId(), 400, 400).toString();
//after getting the profile url you can easily set this to image view using Glide or retrofit library.
                                    }

                                    Log.v("completeObjInfo",obj);
                                    Log.v("TAGObjectInfo","id: "+id);
                                    Log.v("TAGObjectInfo","name: "+name);
                                    Log.v("TAGObjectInfo","email: "+email);
                                    Log.v("TAGObjectInfo","birthday: "+birthday);
                                    Log.v("TAGObjectInfo","gender: "+gender);
                                    Log.v("TAGObjectInfo","profileURL: "+profileURL);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender,birthday");                    
//set these parameter
                request.setParameters(parameters);
                request.executeAsync();                                 
//exuecute task in seprate thread
            }

            @Override
            public void onCancel() {
                //App code
                Log.v("MainActivity", "cancel");
            }

            @Override
            public void onError(FacebookException exception) {
                //App code
                Log.v("MainActivity", exception.getCause().toString());
            }
        });

    }

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

11. Run the app

That is everything there is to it. Now all you have to do is run the script.

Post a Comment

Previous Post Next Post