How to create a Facebook login using an Android App?

In this article, it is explained how to create an Android App that has a Facebook login in it.

There are various social login features to use in Android applications. Here we will learn social login using Facebook, so need to integrate Facebook SDK in project to make use of Facebook login.

Below are the various steps on how to do it;

  1. First thing you need to do is to have Facebook Developer Account and then create a new app.

    Create app on Facebook Console

  2. Install Android Studio(>= 3.0) and then open/create a project where you want to add Facebook login.
  3. In your project, add the following code in your Gradle Scripts -> build.gradle (Project).
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    buildscript{
        repositories {
            jcenter()
        }
    }

    chevron_right

    
    

  4. Now, add the following code in Gradle Scripts -> build.gradle (Module:app) with the latest version of Facebook Login SDK in your project.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  5. Sync your project
  6. Now open app -> res -> values -> strings.xml file to add the following lines and replace the [APP_ID] with your APP_ID, which you can get from Facebook Developer console.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  7. Open app -> manifest -> AndroidManifest.xml file and add this line outside of application element.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  8. Add this meta-data element inside your application element in AndroidManifest.xml file:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  9. Now first thing you require is Key Hash, so add these lines in your activity class before Facebook login code:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    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) {
        }
    }

    chevron_right

    
    

  10. Now run your application in your emulator or on your connected device. You will see Key Hash value printed in logcat, save this for later requirement.
  11. Go to Facebook Developers console and choose setting -> Basic -> Add Platform (in bottom of page) and a popup will opens up to select a platform. Choose Android as a platform.
  12. Add your project package name under ‘Google Play Package Name’. Add class name where login will implement in project like ‘LoginActivity’ and also add the key hash value under ‘Key Hashes’.

    Facebook android login details page

  13. Now back to android studio, add this custom button in your *.xml layout file:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <Button
        android:id="@+id/button_facebook"
        style="@style/FacebookLoginButton"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="15dp"
        android:text="Continue With Facebook"
        android:textAllCaps="false"
        android:textColor="@android:color/white" />

    chevron_right

    
    

  14. Add this code in app -> res -> styles.xml file:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <style name="FacebookLoginButton">
        <item name="android:textSize">14sp</item>
        <item name="android:background">@drawable/facebook_signin_btn</item>
        <item name="android:paddingTop">11dp</item>
        <item name="android:paddingBottom">11dp</item>
        <item name="android:paddingLeft">15dp</item>
        <item name="android:layout_marginLeft">3dp</item>
        <item name="android:layout_marginRight">3dp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_gravity">center_horizontal</item>
    </style>

    chevron_right

    
    

  15. You can customize this button accordingly or instead of an above custom button, you can use the Facebook default button also as Facebook LoginButton.
  16. Make drawable file named ‘bg_button_facebook.xml’ in app -> res -> drawable folder and paste below code:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?xml version="1.0" encoding="utf-8"?>
    <shape
    android:shape="rectangle">
        <corners android:radius="5dp"/>
        <solid android:color="#3B5998"/>
    </shape>

    chevron_right

    
    

  17. Now initialize button in *.java file and some code to initialize Facebook SDK also:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // 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"));
                }
            });
        ...
    }
      
    ...

    chevron_right

    
    

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

    edit
    close

    play_arrow

    link
    brightness_4
    code

    public void facebookLogin()
    {
      
        loginManager
            = LoginManager.getInstance();
        callbackManager
            = CallbackManager.Factory.create();
      
        loginManager
            .registerCallback(
                callbackManager,
                new FacebookCallback<LoginResult>() {
      
                    @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());
                    }
                });
    }

    chevron_right

    
    

  19. Now add another required method ‘disconnectFromFacebook’ for login integration, similarly add this to outside onCreate. This is used to disconnect application from Facebook as no need to stay connected.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    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();
    }

    chevron_right

    
    

  20. Add ‘onActivityResult’ method outside onCreate in same activity:
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

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

    chevron_right

    
    

  21. Now you are done with the coding. Run your application in you device or emulator. You can now login with Facebook also in your application.
  22. If you want to upload your app on play store, then you have to enable ‘status’ from top right section on Facebook for Developers, for this first add privacy policy url in settings -> Basic as per given in below screenshot. Now save the changes and enable status from dashboard.

    Facebook login Privacy Policy url

Attention reader! Don’t stop learning now. Get hold of all the important Java and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.