Connect with us

Hi, what are you looking for?

Latest

Android’s Facebook login example

In our last tutorial we talked about adding Google Connect to the Android application, which was very well received by all our readers. There is no doubt that Google Connect prefers the authentication method for every Android application, but there is another authentication that is very popular among users – Facebook Connect. Facebook is the largest social network in the world with more than 2 billion users. When you add a Facebook connection to your application, it opens its doors to a wide range of users, and this example of a Facebook connection will teach you the same thing

In this Facebook login example you will learn how to register your application on Facebook and how to implement the connection and disconnection of the Androidapplication.

Step 1: Add the dependency on the scale

Add the following dependency to the build.gradle application layer

  1. Introduction com.facebook.android: facebook-login: [4,5].

Step 2: Connecting to Facebook

  • Before we start with the Facebook login example, we must first go to the Facebook Developer Platform. Then click on the My Requests button in the upper right corner and select Add New Request.
  • A dialog box appears in which we enter the display name and email address of the contact and click Create Application ID.
  • Click the Create application button to open the toolbar. Now select Settings on the left and click Add Platform and select Android as Platform.
  • Indicate the name of the dossier and the name of the class of your application. You can get the name of the package for your AndroidManifest.xml file.
  • Now we need to generate a hash key for our application.Generating the hash of the development key
    To generate a hash of the development key, execute the following command on the command line in the Java SDK folder
    1. key tool -exportcert -alias androiddebugkey -keystore C:user\USERNAME.androiddebug.keyystore | PATH_TO_OPENSSL_LIBRARY\\\\openssl sha1 -binary | PATH_TO_OPENSSL_LIBRARY\bin\openssl base64
  • This command creates a 28-character key hash unique to your development environment. Copy and paste it into the field below. You must provide a hash key for the development environment for each person working on your application.
  • Generation
    Android applications must be digitally signed with the version key before they can be downloaded from the store. To create a hash of your Share Key, run the following command on a Mac or Windows, replacing the nickname of your Share Key with the path to your keyboard’s storage space:
    1. key tool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64

Step 3: Facebook IDapplication added

  • We will now enter the App-ID created in the step above into the strings.xml string file of our application.Besides the App-ID we will also create another resource-string by adding fb at the beginning of the App-ID with the name fb_login_protocol_scheme.
    1. FACEBOOK-APP-ID
    2. fbFACEBOOK-APP-ID
  • Add your request to AndroidManifest.xmlas follows
    1. android:[email protected]/facebook_app_id/>
    2. android:configChanges=keypadHidden|screen layout|screen format|orientation
    3. android:[email protected]/app_name />
    4. android: name=com.facebook.customTabActivity
    5. android: export= true>
    6. [email protected]/fb_login_protocol_scheme />

Step 4: Floor plan

  • We have a simple layout with two TextViews and ImageView for our activities. TextViews is a view of the user’s name and email, while ImageView is a view of the user’s image.
  • The most important thing is that we also add the Facebook login button to the layout file. This button is the login of the Facebook library we added for this project.
    1. xmlns:tools=http://schemas.android.com/tools
    2. android: layout_width=match_parent
    3. android: layout_height=match_parent
    4. tools:context=.LoginActivity>.
    5. android: layout_width=wrap_content
    6. android:[email protected]+id/image_view
    7. tools:[email protected]/ic_launcher
    8. android: layout_marginTop=40dp
    9. android: layout_centerHorizontal=true
    10. android: layout_height=wrap_content />
    11. android:[email protected]+id/image_view
    12. android: layout_margin=10dp
    13. android: layout_centerHorizontal=true
    14. android: layout_width=wrap_content
    15. android: [email protected]+id/display_name
    16. android: [email protected]: color/black
    17. android: layout_height=wrap_content />
    18. android: [email protected]/display_name
    19. android: layout_width=wrap_content
    20. android: layout_margin=5dp
    21. android: layout_centerHorizontal=true
    22. android: [email protected]+id/e-mail
    23. android: layout_height=wrap_content />
    24. android:[email protected]+id/login_button
    25. android: layout_width=wrap_content
    26. android: layout_height=wrap_content
    27. android: layout_centerInParent=true />

Step 5

  • When all settings are set, this is the most important step in the Facebook login example. We now initialize the LoginButton in our Java file and set the reading permissions as shown below. The LoginButton is a part of the user interface that summarizes the available functions in Facebook LoginManager. When someone presses a button, the connection is initiated with the defined rights.
  • The login button follows the login status and displays the correct text based on another person’s authentication status. This means that the text of the login button changes if the user is already logged in and acts as a logout button.
    1. the public class LoginActivity extends AppCompatActivity {
    2. the LoginButton loginButton private button ;
    3. Private TextView displayName, e-mail ID ;
    4. Private image displayImage ;
    5. @Overwrite
    6. protected hole onCreate(Bundle storedInstanceState) {
    7. create super.onCreate(savedInstanceState) ;
    8. setContentView(R.layout.activity_login) ;
    9. displayName = findViewById(R.id.display_name) ;
    10. emailID = findViewById(R.id.email) ;
    11. displayImage = findViewById(R.id.image_view) ;
    12. loginButton = findViewById(R.id.login_button) ;
    13. loginButton.setReadPermissions(Arrays.asList(email, public_profile)) ;
    14. }
    15. }

Facebook Login button

Facebook Login button

Recall Manager

  • CallbackManageris registered to process a response when the user presses the login button. CallbackManager can be created by callingCallbackManager.Factory.create() , as shown below.
  • If the connection was successful, the LoginResult setting is provided via the CallbackManager. This is the newAccessTokenwith the last allowed or refused rights. You can use the LoginResult token using the API getAccessToken() as shown below.
    1. Personal callback manager ;
    2. the LoginButton loginButton private button ;
    3. Private TextView displayName, e-mail ID ;
    4. Private image displayImage ;
    5. @Overwrite
    6. protected hole onCreate(Bundle storedInstanceState) {
    7. create super.onCreate(savedInstanceState) ;
    8. setContentView(R.layout.activity_login) ;
    9. displayName = findViewById(R.id.display_name) ;
    10. emailID = findViewById(R.id.email) ;
    11. displayImage = findViewById(R.id.image_view) ;
    12. loginButton = findViewById(R.id.login_button) ;
    13. loginButton.setReadPermissions(Arrays.asList(email, public_profile)) ;
    14. // Creation of the CallbackManager/
    15. callbackManager = CallbackManager.factory.create() ;
    16. // Register the CallbackManager with the login button.
    17. loginButton.registerCallback(callbackManager, new FacebookCallback() {)
    18. @Overwrite
    19. publicly void onSucces(LoginResult loginResult loginResult) {
    20. // Restore the access token with LoginResult
    21. AccessToken accesssToken = loginResult.getAccessToken() ;
    22. }
    23. @Overwrite
    24. Cancel the public void() {
    25. }
    26. @Overwrite
    27. public null and void onError (Facebook exception error) {
    28. }
    29. });
    30. }
  • Finally, in the onActivityResult method you can call callbackManager.onActivityResult to report the results of your FacebookSDK connection via callbackManager.
    1. @Overwrite
    2. public void onActivityResult (int requestCode, int resultrCode, intention data) {
    3. callbackManager.onActivityResult (requestCode, resultCode, data) ;
    4. super.onActivityResult (requestCode, resultrCode, data) ;
    5. }
  • If we receive an AccessToken after the registration of a user, we can easily request their personal data (for which they have given their consent).
    1. private, invalid use ofLoginInformation (AccessToken accessToken) {
    2. /**
    3. Create an imageRequest information for the user
    4. 1. Pair – AccessTokin
    5. 2nd Param – callback (which will be called as soon as the application is successfully completed)
    6. **/
    7. GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {)
    8. //OnCompleted is called after GraphRequest is successfully completed.
    9. @Overwrite
    10. public null and void uncompleted(JSONObject, GraphResponse response) {
    11. try
    12. Line name = object.getString(name) ;
    13. Email string = object.getString(email) ;
    14. String image = object.getJSONObject(image).getJSONObject(data).getString(url) ;
    15. displayName.setText(name) ;
    16. emailID.setText(E-Mail) ;
    17. Capture (JSONException e) {
    18. e.printStackTrace() ;
    19. }
    20. }
    21. });
    22. // We define the parameters of GraphRequest using the software package.
    23. Package parameter = new package() ;
    24. parameters.putString(fields,id,name,email,image.width(200)) ;
    25. request.setParameter ;
    26. // Start a GraphRequest/request.
    27. request.executeAsync() ;
    28. }
  • Basically we make a new GraphRequest with an access token and register the listener to process the response. We analyze the response we received from JSON and obtain the username, email address, username and the URL of the Facebook image. You can now use this data to register a user in your application.
  • This method useLoginInformation() is called by the CallbackManager listener to display the details after a user has successfully logged in. Look at the following code fragment for reference.
    1. loginButton.registerCallback(callbackManager, new FacebookCallback() {)
    2. @Overrite
    3. publicly void onSucces(LoginResult loginResult loginResult) {
    4. AccessToken accesssToken = loginResult.getAccessToken() ;
    5. UsageLoginInformation (accessToken) ;
    6. }
    7. @Overrite
    8. Cancel the public void() {
    9. }
    10. @Overwrite
    11. public null and void onError (Facebook exception error) {
    12. }
    13. });

Output button

Output button

The screenshots above show the login status after the user has logged in, as you can see the changes in the login button to log out and we have received his username and email.

Input status check

  • Only one Facebook user can connect to your application at a time. Once a user has logged in, he will not log out until the access mark has expired. This essentially means that the connection status remains intact even if the application is terminated.
  • As already mentioned, the connection status is automatically displayed in the connection buttonButton . The text of the button automatically changes to Exit, and the button acts as an exit button after the user has logged in. You also need to change the behavior of your application if the user is already logged in.
  • In this section we will check if the user is already logged in to the onStart() method.  If the user is already logged in, we immediately send him/her a request with a registered token and display the data.
  • Below we use theaccess token .getCurrentAccessToken(). This API returns the access mark to the current application when the user is logged in. Otherwise it brings it back to zero.
    1. public omission onStart() {
    2. super.onStart() ;
    3. AccessToken access token = AccessToken.getCurrentAccessToken() ;
    4. as (accessToken != zero) {
    5. UsageLoginInformation (accessToken) ;
    6. }
    7. }

Implementation of the output system

  • As mentioned above, the LoginButton works as a logout button after a user has successfully registered in , and the user logs out when he clicks on it.
  • You can also have a custom button to log out and set a custom output with LoginManager as described in the next section.
    1. LoginManager.getInstance().logOut() ;

Version of AccessTokenTracker

  • The CallbackManager implementation works well if you only want to process user logins. The problem with the implementation is that theCallbackManager stored in LoginButton is not called when a user logs out.
  • We can use AccessTokenTrackerto notify the user when he unsubscribes. AccessTokenTracker is a class offered by FacebookSDK that is used to receive notifications of changes to the access mark. The basic rule is this one: When a user logs out, the access mark is set to zero and the implementation of the AccessTokenTracker is reported.
  • The first step is to expand the AccessTokenTracker class and replace themethod onCurrentAccessTokenChanged(). This method is called every time an access mark is changed.
  1. the public class LoginActivity extends AppCompatActivity {
  2. private accessTokenTracker accessTokenTracker ;
  3. the LoginButton loginButton private button ;
  4. Private TextView displayName, e-mail ID ;
  5. Private image displayImage ;
  6. @Overwrite
  7. protected hole onCreate(Bundle storedInstanceState) {
  8. create super.onCreate(savedInstanceState) ;
  9. setContentView(R.layout.activity_login) ;
  10. displayName = findViewById(R.id.display_name) ;
  11. emailID = findViewById(R.id.email) ;
  12. displayImage = findViewById(R.id.image_view) ;
  13. loginButton = findViewById(R.id.login_button) ;
  14. loginButton.setReadPermissions(Arrays.asList(email, public_profile)) ;
  15. // Definition of AccessTokenTracker/
  16. accessTokenTracker = new AccessTokenTracker() {
  17. // This method is invoked each time the access mark is changed.
  18. @Overrite
  19. protected null and void onCurrentAccessTokenChanged (AccessToken oldAccessToken, AccessToken currentAccessToken) {
  20. UsageLoginInformation(currentAccessToken) ;
  21. }
  22. };
  23. }
  24. }
  • A simple AccessTokenTracker extension will not start the search.  To start tracking you must explicitly call accesssTokenTracker.startTracking() . We call it in methodonStart() to start with tracking.
    1. public omission onStart() {
    2. super.onStart() ;
    3. // It starts by following the access mark //
    4. accessTokenTracker.startTracking() ;
    5. AccessToken access token = AccessToken.getCurrentAccessToken() ;
    6. UsageLoginInformation (accessToken) ;
    7. }
  • It is also important to stop monitoring before the activity is destroyed. This is done with accesssTokenTracker.stopTracking() in the method onDestroy() .
    1. public loophole onDestroy() {
    2. Super.onDestroy() ;
    3. // We stop the chase before we destroy the case.
    4. accessTokenTracker.stopTracking() ;
    5. }
  • If you use AccessTokenTracker, you don’t need to implement the CallbackManager at all. As mentioned before, the implementation of AccessTokenTracker happens every time the access mark changes. This means that even if a user enters the tracker, the new AccessToken will be activated. Take care of it, as shown below.
    1. private accessTokenTracker accessTokenTracker ;
    2. @Overrite
    3. protected hole onCreate(Bundle storedInstanceState) {
    4. create super.onCreate(savedInstanceState) ;
    5. setContentView(R.layout.activity_login) ;
    6. displayName = findViewById(R.id.display_name) ;
    7. emailID = findViewById(R.id.email) ;
    8. displayImage = findViewById(R.id.image_view) ;
    9. loginButton = findViewById(R.id.login_button) ;
    10. loginButton.setReadPermissions(Arrays.asList(email, public_profile)) ;
    11. callbackManager = CallbackManager.factory.create() ;
    12. accessTokenTracker = new AccessTokenTracker() {
    13. @Overwrite
    14. protected null and void onCurrentAccessTokenChanged (AccessToken oldAccessToken, AccessToken currentAccessToken) {
    15. // currentAccessToken is zero if the user has logged out.
    16. if (currentAccessToken != null) {
    17. // A non-zero access token means that the user is logged in, which is why we use GraphRequest.
    18. UsageLoginInformation(currentAccessToken) ;
    19. Ilsa
    20. displayName.setText (unregistered) ;
    21. }
    22. }
    23. };
    24. }

Conclusion

This concludes our example of connecting to Facebook. Feel free to ask questions in the comments, and if you want to read other tutorials like this one, check out the Android examples. Every week we publish a new tutorial for Android.

 

 

 

 facebook login integration in android example,android login with facebook and google example,firebase facebook login android,facebook integration in android kotlin,custom facebook login button android,facebook integration in android simplified coding,facebook login button android xml,facebook login sdk

You May Also Like