Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android Facebook Login Example [Tutorial]

In our last tutorial we discussed about adding Google Login to Android App which was very well received by all our readers. Without doubt Google Login is the most preferred authentication method for every Android App, but there is one more authentication which is very popular among users- Facebook Login. Facebook is the biggest social media network in the world with more that 2 billion users. Adding Facebook Login in your app will open its doors to a wide range of users and this facebook login example will teach you the same

In this Facebook Login example you will  learn how to register your application with Facebook and implement Login and logout in your Android Application

Step 1 : Add gradle dependency

Add the following dependency to app level build.gradle

implementation 'com.facebook.android:facebook-login:[4,5)'

Step 2 : Register with Facebook

  • Before beginning with Facebook Login Example first we need to go to Facebook Developer Platform . Then click on My Apps on top right side and select “Add new App”
  • A pop-up dialog appears where we enter “Display Name” and “Contact email” and click “Create App ID”
  • On clicking “Create App ID” you are taken to a dashboard. Now select Settings from the left side pane and click “Add Platform” and select Android as the platform.
  • Enter package name and class name of your app. You can get the package name for your AndroidManifest.xml file.
  • Now we need to generate key- hash for our app.Generating a Development Key Hash
    To generate a development key hash, run the following command in a command prompt in the Java SDK folder:
    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 command will generate a 28-character key hash unique to your development environment. Copy and paste it into the field below. You will need to provide a development key hash for the development environment of each person who works on your app.

    Generating a Release Key Hash
    Android apps must be digitally signed with a release key before you can upload them to the store. To generate a hash of your release key, run the following command on Mac or Windows substituting your release key alias and the path to your keystore:

    keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64

Step 3: Adding Facebook App ID

  • We will now enter the App ID created in the above step in our app’s strings.xml. Apart from the App ID we alse create one more string resource by  appending ‘fb’ at the beginning of app-id by the name fb_login_protocol_scheme.
    FACEBOOK-APP-IDfbFACEBOOK-APP-ID
  • Add the following in your app’s AndroidManifest.xml

Step 4 : Designing the Layout

  • We have a simple layout with a two TextViews and an ImageView for our activity. TextViews are to display name and email whereas ImageView is to display the picture of the user.
  • More importantly, we also add the facebook login button to the the layout file. This Login button is from the facebook library we added for this project.

Step 5

  • With all the setup done, this is the most important step of Facebook Login example. Now we initialize the LoginButton in our java file and set the read permissions as shown below. The LoginButton is a UI element that wraps functionality available in the Facebook’s LoginManager. When someone clicks on the button, the login is initiated with the permissions set.
  • The Login button follows the login state, and displays the correct text based on someone’s authentication state. This means that the text on the login button changes when the user has already logged in and it acts as a logout button.
    public class LoginActivity extends AppCompatActivity {
    
        private LoginButton loginButton;
        private TextView displayName, emailID;
        private ImageView displayImage;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_login);
    
            displayName = findViewById(R.id.display_name);
            emailID = findViewById(R.id.email);
            displayImage = findViewById(R.id.image_view);
            loginButton = findViewById(R.id.login_button);
            loginButton.setReadPermissions(Arrays.asList("email", "public_profile"));
    
    
        }
    }
Facebook Sign In Button

CallbackManager

  • CallbackManager   is registered to handled the response when the user clicks login button. CallbackManager can be created by calling CallbackManager.Factory.create()  as shown below. Once created it should then  be registered with the login button.
  • On successfully logging in, a LoginResult parameter is received via CallbackManager. This has the new AccessToken with the most recently granted or declined permissions. You can get access token from LoginResult using the getAccessToken() API as shown below
    private CallbackManager callbackManager;
    private LoginButton loginButton;
    private TextView displayName, emailID;
    private ImageView displayImage;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    
        displayName = findViewById(R.id.display_name);
        emailID = findViewById(R.id.email);
        displayImage = findViewById(R.id.image_view);
        loginButton = findViewById(R.id.login_button);
        loginButton.setReadPermissions(Arrays.asList("email", "public_profile"));
    
        // Creating CallbackManager
        callbackManager = CallbackManager.Factory.create();
    
        // Registering CallbackManager with the LoginButton
        loginButton.registerCallback(callbackManager, new FacebookCallback() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // Retrieving access token using the LoginResult
                AccessToken accessToken = loginResult.getAccessToken();
    
            }
    
            @Override
            public void onCancel() {
    
            }
    
            @Override
            public void onError(FacebookException error) {
    
            }
        });
    
    }
  • Finally in your onActivityResult method, call callbackManager.onActivityResult to pass the login results to the FacebookSDK  via callbackManager.
    @Override
    public void onActivityResult(int requestCode, int resulrCode, Intent data) {
        callbackManager.onActivityResult(requestCode, resulrCode, data);
        super.onActivityResult(requestCode, resulrCode, data);
    }
    
  • Once we have the AccessToken after user logs in we can easily query for his personal details (for which he has granted permissions).
    private void useLoginInformation(AccessToken accessToken) {
    
         /**
          Creating the GraphRequest to fetch user details
           1st Param - AccessToken
           2nd Param - Callback (which will be invoked once the request is successful) 
         **/
          GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
              //OnCompleted is invoked once the GraphRequest is successful
              @Override
              public void onCompleted(JSONObject object, GraphResponse response) {
                  try {
                      String name = object.getString("name");
                      String email = object.getString("email");
                      String image = object.getJSONObject("picture").getJSONObject("data").getString("url");
                      displayName.setText(name);
                      emailID.setText(email);
                  } catch (JSONException e) {
                      e.printStackTrace();
                  }
              }
          });
    
          // We set parameters to the GraphRequest using a Bundle.   
          Bundle parameters = new Bundle();
          parameters.putString("fields", "id,name,email,picture.width(200)");
          request.setParameters(parameters);
          // Initiate the GraphRequest
          request.executeAsync();
      }
    
  • Basically we create a new GraphRequest using the Access Token and register a listener to handle the response. We parse the JSON response received and  get the facebook username, email, user id and picture URL. You can now use these details to register the user in your app.
  • This useLoginInformation() method is called from the CallbackManager listener to display details once the user has successfully logged in. Look at the code snippet below for reference
    loginButton.registerCallback(callbackManager, new FacebookCallback() {
           @Override
           public void onSuccess(LoginResult loginResult) {
               AccessToken accessToken = loginResult.getAccessToken();
               useLoginInformation(accessToken);
               
    
           }
    
           @Override
           public void onCancel() {
    
           }
    
           @Override
           public void onError(FacebookException error) {
    
           }
       });
Logout Button

Above screenshots represents app’s state after the user has logged in, as you can see the login button changes to logout and we fetch his username and email

Checking Login Status

  • Only one Facebook user at a time can be logged in into your  app. Also once a user has logged in he is not logged out unless the access token expires. This basically means that the login status remains intact even if the app is killed.
  • As already mentioned the login status is automatically reflected in the LoginButton. The text on the button automatically changes to “Logout” and button acts as the logout button once the user has logged in. Similarly you need to modify the behavior of your app if the user is already logged in.
  • In this section we will be checking if the  user has already logged in in the onStart() method.  If user is already logged in  we directly send a request using the saved Access Token and display the details.
  • We use AccessToken.getCurrentAccessToken() below. This API will return the current access token for the application if the user is logged in. If not it will return null.
    public void onStart() {
        super.onStart();
        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        if (accessToken != null) {
             useLoginInformation(accessToken);
        }
    }

Logout Implementation

  • As already mentioned above, once then user successfully logs in the LoginButton works as a Logout button and the user is logged out after clicking it.
  • You can also have a custom button for logout and implement  user logout using the LoginManager as shown in the snippet below
    LoginManager.getInstance().logOut();
    

AccessTokenTracker implementation

  • CallbackManager implementation works fine when you only want to handle user login. Issue with its implementation is that CallbackManager registered with LoginButton is not invoked when the user logs out .
  • To be notified when the user logs out we can use AccessTokenTracker. AccessTokenTracker  is a class provided by FacebookSDK and is used to receive notification for any changes in Access Token. Basically when the user logs out the access token changes to null and your AccessTokenTracker implementation is notified.
  • First step is to extend AccessTokenTracker class and override the onCurrentAccessTokenChanged() method. This method is invoked everytime the access token changes.
public class LoginActivity extends AppCompatActivity {

    private AccessTokenTracker accessTokenTracker;
    private LoginButton loginButton;
    private TextView displayName, emailID;
    private ImageView displayImage;

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

        displayName = findViewById(R.id.display_name);
        emailID = findViewById(R.id.email);
        displayImage = findViewById(R.id.image_view);
        loginButton = findViewById(R.id.login_button);
        loginButton.setReadPermissions(Arrays.asList("email", "public_profile"));

        // Defining the AccessTokenTracker
        accessTokenTracker = new AccessTokenTracker() {
            // This method is invoked everytime access token changes
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
                   useLoginInformation(currentAccessToken);
               
            }
        };

    }

}
  • Just extending AccessTokenTracker wont start the tracking.  You need to explicitly call  accessTokenTracker.startTracking() for the tracking to start . We call it in the onStart() method to initiate the tracking.
    public void onStart() {
        super.onStart();
        //This starts the access token tracking
        accessTokenTracker.startTracking();
        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        useLoginInformation(accessToken);
        
    
    }
    
  • Also its important to stop the tracking before the activity is destroyed . This is done using  accessTokenTracker.stopTracking() in the onDestroy() method.
    public void onDestroy() {
        super.onDestroy();
        // We stop the tracking before destroying the activity
        accessTokenTracker.stopTracking();
    
    }
  • If you are using AccessTokenTracker you don’t need to implement CallbackManager at all. As already mentioned AccessTokenTracker implementation will be triggered for any change in Access-Token. This means even when the user logs in the tracker will be triggered with the new AccessToken. You just need to handle it as shown below
    private AccessTokenTracker accessTokenTracker;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    
        displayName = findViewById(R.id.display_name);
        emailID = findViewById(R.id.email);
        displayImage = findViewById(R.id.image_view);
        loginButton = findViewById(R.id.login_button);
        loginButton.setReadPermissions(Arrays.asList("email", "public_profile"));
    
        callbackManager = CallbackManager.Factory.create();
    
        accessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
                // currentAccessToken is null if the user is logged out 
                if (currentAccessToken != null) {
                    // AccessToken is not null implies user is logged in and hence we sen the GraphRequest
                    useLoginInformation(currentAccessToken);
                }else{
                    displayName.setText("Not Logged In");
                }
            }
        };
    }

Conclusion

This finishes our Facebook Login example. Feel free to ask any questions in the comments and if you would like to read more tutorials like these please visit Android Examples. We publish a new Android tutorial every week

The post Android Facebook Login Example [Tutorial] appeared first on AndroidClarified.



This post first appeared on Android Clarified, please read the originial post: here

Share the post

Android Facebook Login Example [Tutorial]

×

Subscribe to Android Clarified

Get updates delivered right to your inbox!

Thank you for your subscription

×