Steps for Facebook Login in android.

Total Post:24

Points:170
 852  View(s)
Ratings:
Rate this:

Step by step guide for Facebook Login in android.

  1. Post:24

    Points:170
    Re: Steps for Facebook Login in android.

    For Facebook login in android, first of all, register your app.

    Registering Your Facebook App 

    Step 1:  First you log in using your Facebook account to https://developers.facebook.com/apps/.

    Steps for Facebook Login in android.

    Step 2: Click on create a new app. And set the app name and the email id as shown in the below pic.

    Steps for Facebook Login in android.

    Step 3:  You shall see the dashboard in the next screen. Choose Facebook Login Setup and select the platform as Android as shown in the below images. 

    Steps for Facebook Login in android.

    Step 4:    After that, add the following dependencies in your app‘s build.gradle. 

    
    buildscript {  
    repositories {
    mavenCentral()
    }
    }  

    Step 5: Use the latest version of the SDK dependency. 

    implementation 'com.facebook.android:facebook-android-sdk:4.31.0' 
    or  
    implementation 'com.facebook.android:facebook-android-sdk:[4,5)'

    Step 6:     To check the SDK is successfully added in our project add the following import statements in your MainActivity.java class file as shown below. If there’s no error, the build was successful. 

    import com.facebook.FacebookSdk; 
    import com.facebook.appevents.AppEventsLogger;

    Step 7:    Add your Facebook App ID in the string.xml file.

    <string name="facebook_app_id">2048405422006344</string>
    
    <string name="fb_login_protocol_scheme">fb2048405422006344</string>

    Step 8:    Enter your package name and default activity name with the fully qualified path as shown below. After saving click on Use this package name to confirm. 

    Steps for Facebook Login in android.

    Step 9:    The next window asks for the add key hashes. That can be done by running the following commands on windows cmd. 

    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

     You will need the following steps for generating a hash key.

      1.   Download OpenSSL library for Windows from the https://code.google.com/archive/p/openssl-for-windows/downloads.

      2.  Open your java bin path location and copy it. And after that open cmd and write some command .

          Cd C:\Program Files\Java\jdk-9.0.4\bin (click enter)

         Write some key tool command-

       keytool -exportcert -alias androiddebugkey -keystore "C:\Users\msclient009\.android\debug.keystore" | "C:\openssl-0.9.8e_X64\bin\openssl" sha1 -binary | "C:\openssl-0.9.8e_X64\bin\openssl" base64 

    Above command will generate a 28-character key hash unique to your development environment. And after that add key hashes in your Facebook page.

    Step 10:   Add internet permissions in the AndroidManifest.xml file by adding the following line in the manifest file. 

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

    Step 11:    Add Following meta-data tag in your 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" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>

    Step 12:   Add some code in your activity_main.xml file

    <FrameLayout
    
        android:id="@+id/FrameLayout1"
        android:layout_width="match_parent"
        android:layout_height="@dimen/button_height"
        android:layout_below="@+id/sign_in_button"
        android:layout_marginTop="@dimen/card"
        android:layout_weight="1"
        android:background="@drawable/login_button"
        android:elevation="3dp">
        <com.facebook.login.widget.LoginButton
            android:id="@+id/fb_login_button"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="@dimen/bottom"
            android:background="#4285F4"
            android:textSize="@dimen/text_size" />
        <Button
            android:id="@+id/fb"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:background="#4285F4"
            android:drawableStart="@drawable/fb_icon"
            android:padding="@dimen/bottom"
            android:text="@string/com_facebook"
            android:textColor="@color/back"
            android:textSize="@dimen/text_size" />
    </FrameLayout>

    MainActivity.java file

    loginButton = (LoginButton) findViewById(R.id.fb_login_button);
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);
    callbackManager = CallbackManager.Factory.create(); // create instance of callback manager class
    if (Utils.isNetworkAvailable(getApplicationContext())) {
       loginButton.setReadPermissions(Arrays.asList(EMAIL, PUBLIC_PROFILE));
        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
              accessTokenFacebook = loginResult.getAccessToken();
                final GraphRequest request = GraphRequest.newMeRequest(accessTokenFacebook, new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.i("GraphResponse", response.toString());
                        Log.i("JSONObject", object.toString());
                        // Get facebook data from login
                        String email="";
                        try {
                           String userName = object.getString("name");
                           String id = object.getString("id");
                           email=object.getString("email");
                            String firstName = " ", lastName = " ";
                            if (userName != null) {
                                int end = userName.lastIndexOf(' ');
                                if (end >= 0) {
                                    firstName = userName.substring(0, end);
                                    lastName = userName.substring(end + 1, userName.length());
                                }
                            }
                            Toast.makeText(getApplicationContext(),"Facebook Login Successful",Toast.LENGTH_SHORT).show();
                            if(email.equals("")) {
    Toast.makeText(getApplicationContext(),getResources().getString(R.string.email_permission),Toast.LENGTH_SHORT).show();
                            }
                            else {
                                loginApi("facebook", id, firstName, lastName, email);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email"); // Add some field as per user requirement
                request.setParameters(parameters);
                request.executeAsync();
            }
            @Override
            public void onCancel() {
                Log.d("facebook Login","On cancel");
            }
            @Override
            public void onError(FacebookException error) {
                Log.v("Error", error.toString());
            }
        });
    } else {
        Toast.makeText(this, getResources().getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
    }
    // Login Api AsyncTask Code
    public void loginApi(String provider, String providerId, String firstName, String lastName, String emailId) {
        LoginAsyncTask asyncTask = new LoginAsyncTask(getApplicationContext(), provider, providerId, firstName, lastName, emailId);
        asyncTask.delegate = this;
        asyncTask.execute();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v("Request Code", String.valueOf(requestCode));
        if (requestCode == REQ_CODE_GOOGLE_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            handleSignInResult(task);
        }
       if(requestCode == REQ_CODE_FB_SIGN_IN){
           callbackManager.onActivityResult(requestCode, resultCode, data);
        }
    }

Answer

Please check, If you want to make this post sponsored

You are not a Sponsored Member. Click Here to Subscribe the Membership.