Pull Facebook Feed Into Android Studio

How to create a Facebook login using an Android App?

View Discussion

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Like Article

    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).

      buildscript{

      repositories {

      jcenter()

      }

      }

    4. 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'

      }

    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.

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

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

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

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

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

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

      @Override

      protected void onCreate(Bundle savedInstanceState)

      {

      super .onCreate(savedInstanceState);

      setContentView(R.layout.activity_login);

      ... printHashKey();

      ...

      }

      ...

      public void

      printHashKey()

      {

      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) {

      }

      }

    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:

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

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

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

    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:

      <? xml version = "1.0" encoding = "utf-8" ?>

      < shape

      android:shape = "rectangle" >

      < corners android:radius = "5dp" />

      < solid android:color = "#3B5998" />

      </ shape >

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

      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" ));

      }

      });

      ...

      }

      ...

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

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

      }

      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)

      {

      Log.v( "LoginScreen" , "----onError: "

      + error.getMessage());

      }

      });

      }

    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.

      public void disconnectFromFacebook()

      {

      if (AccessToken.getCurrentAccessToken() == null ) {

      return ;

      }

      new GraphRequest(

      AccessToken.getCurrentAccessToken(),

      "/me/permissions/" ,

      null ,

      HttpMethod.DELETE,

      new GraphRequest

      .Callback() {

      @Override

      public void onCompleted(GraphResponse graphResponse)

      {

      LoginManager.getInstance().logOut();

      }

      })

      .executeAsync();

      }

    20. Add 'onActivityResult' method outside onCreate in same activity:

      @Override

      protected void onActivityResult( int requestCode,

      int resultCode,

      Intent data)

      {

      callbackManager.onActivityResult(

      requestCode,

      resultCode,

      data);

      super .onActivityResult(requestCode,

      resultCode,

      data);

      }

    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


    keltnerdehe1996.blogspot.com

    Source: https://www.geeksforgeeks.org/how-to-create-a-facebook-login-using-an-android-app/

    Belum ada Komentar untuk "Pull Facebook Feed Into Android Studio"

    Posting Komentar

    Iklan Atas Artikel

    Iklan Tengah Artikel 1

    Iklan Tengah Artikel 2

    Iklan Bawah Artikel