Airo Global Software

Think Beyond Future !

How To Create A Facebook Login Page In Android Studio?

- Posted in Android by

enter image description here

There are multiple social login features to use in Android apps. Here we will know about social login using Facebook, so we need to integrate the Facebook SDK in the project to make use of Facebook login.

What are the steps needed to build a Facebook login page?

First thing you need to do is to have a Facebook developer account and then build a new app. Install android studio and open or create a new project where you want to include Facebook login. In your project, include the following code in your Project.

buildscript{
    repositories {
        jcenter()
    }
}

Now, add the following code in Module:app with the new version of Facebook Login SDK in it.

dependencies {
     implementation 'com.facebook.android:facebook-android-sdk:5.0.0'
}

Sync the project Now start with app -> res -> values -> strings.xml file to include the lines and replace the [APP_ID] with your APP_ID, which you can get from Facebook Developer console. Open app -> manifest -> manifest file and add this line outside of the application. Include the meta-data element inside the app element in AndroidManifest.xml file. Now first thing you need is Key Hash, so include these lines in the activity class before Facebook login code:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
  
    ... printHashKey();
    ...
}

...
  
    public void
    printHashKey()
{
  
    // Add code to print out the key hash
    try {
  
        PackageInfo info
            = getPackageManager().getPackageInfo(
                "com.android.facebookloginsample",
                PackageManager.GET_SIGNATURES);
  
        for (Signature signature : info.signatures) {
  
            MessageDigest md
                = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:",
                  Base64.encodeToString(                      md.digest(),
                      Base64.DEFAULT));
        }
    }
  
    catch (PackageManager.NameNotFoundException e) {
    }
  
    catch (NoSuchAlgorithmException e) {
    }
}

Now run the application. You will see Key Hash value in logcat, save this for later needs. Go to Facebook Developers console and choose setting -> Basic -> Add Platform and a popup will open up to select a platform. Select Android as a platform. Include your project package name under ‘Google Play Package Name’. Add the class name where login will be implemented in projects like ‘LoginActivity’ and also include the key hash value under ‘Key Hashes’. Now in android studio, include this personalised button in your *.xml layout file:

Include this code in app -> res -> styles.xml :

You can personalize this button instead of an above custom button, you can use the Facebook button also as Facebook LoginButton. Make a file named ‘bg_button_facebook.xml’ in app -> res -> drawable folder Now make a button in *.java file and some syntax to initialize Facebook SDK :

// Declare variables
private Button mButtonFacebook;
  
private CallbackManager callbackManager;
private LoginManager loginManager;
 ...
      @Override
    protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
     ...
          mButtonFacebook
        = findViewById(R.id.button_facebook);
    FacebookSdk.sdkInitialize(MainActivity.this);
    callbackManager = CallbackManager.Factory.create();
    facebookLogin();
    ...
          mButtonFacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v)
            {
                loginManager.logInWithReadPermissions(
                    MainActivity.this,
                    Arrays.asList(
                        "email",
                        "public_profile",
                        "user_birthday"));
            }
        });
    ...
}
 ...

Add ‘facebookLogin’ option outside onCreate() in the java file. This is the program code for Facebook login response.

public void facebookLogin()
{
      loginManager
        = LoginManager.getInstance();
    callbackManager
        = CallbackManager.Factory.create();
      loginManager
        .registerCallback(
            callbackManager,
            new FacebookCallback() {
                  @Override
                public void onSuccess(LoginResult loginResult)
                {
                    GraphRequest request = GraphRequest.newMeRequest(
                          loginResult.getAccessToken(),
                         new GraphRequest.GraphJSONObjectCallback() {
                              @Override
                            public void onCompleted(JSONObject object,
                                                    GraphResponse response)
                            {
                                  if (object != null) {
                                    try {
                                        String name = object.getString("name");
                                        String email = object.getString("email");
                                        String fbUserID = object.getString("id");
                                          disconnectFromFacebook();
  
                                        // do action after Facebook login success
                                        // or call your API
                                    }
                                    catch (JSONException | NullPointerException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
  
                    Bundle parameters = new Bundle();
                    parameters.putString(
                        "fields",
                        "id, name, email, gender, birthday");
                    request.setParameters(parameters);
                    request.executeAsync();
                }
                  @Override
                public void onCancel()
                {
                    Log.v("LoginScreen", "---onCancel");
                }
                  @Override
                public void onError(FacebookException error)
                {
                    // here write code when get error
                    Log.v("LoginScreen", "----onError: "
                                             + error.getMessage());
                }
            });
}

Now include another needed option ‘disconnectFromFacebook’ for login , similarly add this to onCreate. This is used to disconnect applications from Facebook as there is no need to stay connected.

public void disconnectFromFacebook()
{
    if (AccessToken.getCurrentAccessToken() == null) {
        return; // already logged out
    }
  
    new GraphRequest(
        AccessToken.getCurrentAccessToken(),
        "/me/permissions/",
        null,
        HttpMethod.DELETE,
        new GraphRequest
            .Callback() {
                @Override
                public void onCompleted(GraphResponse graphResponse)
                {
                    LoginManager.getInstance().logOut();
                }
            })
        .executeAsync();
}

Include ‘onActivityResult’ option onCreate in same activity:

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

Now you are finished with the coding. Run your application in your emulator. You can now login with Facebook also in your application. If you have any questions about the above topic or have to get services and consultations and get the best Android application services. Feel free to contact us. AIRO GLOBAL SOFTWARE will be your strong digital partner. E-mail id: [email protected]

enter image description here Author - Johnson Augustine
Chief Technical Director and Programmer
Founder: Airo Global Software Inc
LinkedIn Profile: www.linkedin.com/in/johnsontaugustine/