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;
- First thing you need to do is to have Facebook Developer Account and then create a new app.
- Install Android Studio(>= 3.0) and then open/create a project where you want to add Facebook login.
- In your project, add the following code in your Gradle Scripts -> build.gradle (Project).
buildscript{Â Â Â Ârepositories {Â Â Â Â Â Â Â Âjcenter()Â Â Â Â}} - Now, add the following code in Gradle Scripts -> build.gradle (Module:app) with the latest version of Facebook Login SDK in your project.
dependencies {Â Â Â Â Âimplementation 'com.facebook.android:facebook-android-sdk:5.0.0'} - Sync your project
- 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.
<stringname="facebook_app_id">[APP_ID]</string><stringname="fb_login_protocol_scheme">fb[APP_ID]</string> - Open app -> manifest -> AndroidManifest.xml file and add this line outside of application element.
<uses-permissionandroid:name="android.permission.INTERNET"/> - Add this meta-data element inside your application element in 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"/> - Now first thing you require is Key Hash, so add these lines in your activity class before Facebook login code:
@OverrideprotectedvoidonCreate(Bundle savedInstanceState){   Âsuper.onCreate(savedInstanceState);   ÂsetContentView(R.layout.activity_login);   Â... printHashKey();   Â...}ÂÂ...   Âpublicvoid   Â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 your application in your emulator or on your connected device. You will see Key Hash value printed in logcat, save this for later requirement.
- 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.
- 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’.
- Now back to android studio, add this custom button in your *.xml layout file:
<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"/> - Add this code in app -> res -> styles.xml file:
<stylename="FacebookLoginButton">Â Â Â Â<itemname="android:textSize">14sp</item>Â Â Â Â<itemname="android:background">@drawable/facebook_signin_btn</item>Â Â Â Â<itemname="android:paddingTop">11dp</item>Â Â Â Â<itemname="android:paddingBottom">11dp</item>Â Â Â Â<itemname="android:paddingLeft">15dp</item>Â Â Â Â<itemname="android:layout_marginLeft">3dp</item>Â Â Â Â<itemname="android:layout_marginRight">3dp</item>Â Â Â Â<itemname="android:layout_height">wrap_content</item>Â Â Â Â<itemname="android:layout_gravity">center_horizontal</item></style> - You can customize this button accordingly or instead of an above custom button, you can use the Facebook default button also as Facebook LoginButton.
- Make drawable file named ‘bg_button_facebook.xml’ in app -> res -> drawable folder and paste below code:
<?xmlversion="1.0"encoding="utf-8"?><shapeandroid:shape="rectangle">Â Â Â Â<cornersandroid:radius="5dp"/>Â Â Â Â<solidandroid:color="#3B5998"/></shape> - Now initialize button in *.java file and some code to initialize Facebook SDK also:
// Declare variablesprivateButton mButtonFacebook;ÂÂprivateCallbackManager callbackManager;privateLoginManager loginManager;ÂÂ...   Â@Override   ÂprotectedvoidonCreate(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(newView.OnClickListener() {           Â@Override           ÂpublicvoidonClick(View v)           Â{               ÂloginManager.logInWithReadPermissions(                   ÂMainActivity.this,                   ÂArrays.asList(                       Â"email",                       Â"public_profile",                       Â"user_birthday"));           Â}       Â});   Â...}ÂÂ... - Add ‘facebookLogin’ method outside onCreate() in java file. This is the code for Facebook login response.
publicvoidfacebookLogin(){   ÂloginManager       Â= LoginManager.getInstance();   ÂcallbackManager       Â= CallbackManager.Factory.create();   ÂloginManager       Â.registerCallback(           ÂcallbackManager,           ÂnewFacebookCallback<LoginResult>() {               Â@Override               ÂpublicvoidonSuccess(LoginResult loginResult)               Â{                   ÂGraphRequest request = GraphRequest.newMeRequest(                       ÂloginResult.getAccessToken(),                       ÂnewGraphRequest.GraphJSONObjectCallback() {                           Â@Override                           ÂpublicvoidonCompleted(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 =newBundle();                   Âparameters.putString(                       Â"fields",                       Â"id, name, email, gender, birthday");                   Ârequest.setParameters(parameters);                   Ârequest.executeAsync();               Â}               Â@Override               ÂpublicvoidonCancel()               Â{                   ÂLog.v("LoginScreen","---onCancel");               Â}               Â@Override               ÂpublicvoidonError(FacebookException error)               Â{                   Â// here write code when get error                   ÂLog.v("LoginScreen","----onError: "                                            Â+ error.getMessage());               Â}           Â});} - 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.
publicvoiddisconnectFromFacebook(){   Âif(AccessToken.getCurrentAccessToken() ==null) {       Âreturn;// already logged out   Â}   ÂnewGraphRequest(       ÂAccessToken.getCurrentAccessToken(),       Â"/me/permissions/",       Ânull,       ÂHttpMethod.DELETE,       ÂnewGraphRequest           Â.Callback() {               Â@Override               ÂpublicvoidonCompleted(GraphResponse graphResponse)               Â{                   ÂLoginManager.getInstance().logOut();               Â}           Â})       Â.executeAsync();} - Add ‘onActivityResult’ method outside onCreate in same activity:
@OverrideprotectedvoidonActivityResult(intrequestCode,                               ÂintresultCode,                               ÂIntent data){   Â// add this line   ÂcallbackManager.onActivityResult(       ÂrequestCode,       ÂresultCode,       Âdata);   Âsuper.onActivityResult(requestCode,                          ÂresultCode,                          Âdata);} - 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.
- 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.

