This is the first way of connecting with facebook. You have to register your application and then receive some Application Id , and then you have to download the facebook SDK and add it to your project. The steps are listed below:

For Register go to This Link: – https://developers.facebook.com

 

First Add some files in Mainfest.xml File: –

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="safal.bhatia.facebookintegration">
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProvider1"
            android:exported="true" />
        <!–If you register in facebook developer Account then you see this Facebook Application ID–>
       
<meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />
    </application>
</manifest>

 

Add Dependency: – This dependency is add in (Module:app)

compile 'com.facebook.android:facebook-android-sdk:[4,5)'

 

This Line is add in (Project:Your App Name)
buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
       
// NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
   
}
}

Java File ActivityMain.java: –

package safal.bhatia.facebookintegration;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity {
    private String Keyhash;
    ImageView facebook_login;
    private LoginManager loginManager;
    private CallbackManager callbackManager;
    Activity sActivity;
    TextView txt_facebook;
    private String userId, profileName, firstName, lastName, myEmail, myProfilePic, success, message;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sActivity = MainActivity.this;
        FacebookSdk.sdkInitialize(sActivity);
        AppEventsLogger.activateApp(this);
        callbackManager = CallbackManager.Factory.create();
        txt_facebook = (TextView)findViewById(R.id.txt_facebook);
        txt_facebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginManager.getInstance().logInWithReadPermissions(sActivity, Arrays.asList("user_friends", "public_profile", "email"));
                getUserInfo();
            }
        });
        hashKey();

    }
    public void hashKey() {
        //Generate Hash Key
       
try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    getPackageName(),
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Keyhash = Base64.encodeToString(md.digest(), Base64.DEFAULT);
                Log.e("KeyHash:", Keyhash);
            }
        } catch (PackageManager.NameNotFoundException e) {

        } catch (NoSuchAlgorithmException e) {
        }
    }
    //Facebook Login
   
protected void getUserInfo() {
        loginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {

                String accessToken = loginResult.getAccessToken().getToken();
                Log.i("accessToken", accessToken);

                GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                    @Override
                    public void onCompleted(JSONObject object, GraphResponse response) {
                        Log.e("FacebookActivity", response.toString());
                        Bundle fbData = getFacebookData(object);
                    }
                });

                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,first_name,last_name,email,gender,birthday,location");
                request.setParameters(parameters);
                request.executeAsync();
            }
            @Override
            public void onCancel() {
                System.out.println("On Cancel");
            }
            @Override
            public void onError(FacebookException error) {
                System.out.println("On Error");
                // Log.v("LoginActivity", exception.getCause().toString());
           
}
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //Facebook
       
callbackManager.onActivityResult(requestCode, resultCode, data);
    }
    private Bundle getFacebookData(JSONObject object) {
        try {
            Bundle bundle = new Bundle();
            userId = object.getString("id");
            profileName = object.getString("name");
            myEmail = object.getString("email");
            firstName = object.getString("first_name");
            lastName = object.getString("last_name");
            Log.e("Name", "" + profileName);
            try {
                URL profile_pic = new URL("https://graph.facebook.com/" + userId + "/picture?width=400&height=400");
                Log.i("profile_pic", profile_pic + "");
                bundle.putString("profile_pic", profile_pic.toString());
                myProfilePic = profile_pic.toString();//Get Image Url
           
} catch (MalformedURLException e) {
                e.printStackTrace();
                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Toast.makeText(this, "First Name = "+firstName+"\n" +
                "Last Name = "+lastName+"\n" +
                "Email = "+myEmail+"\n"+
                "Image Url = "+myProfilePic, Toast.LENGTH_SHORT).show();
        return null;
    }
}

 

XML FIle activity_main: –

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context="safal.bhatia.facebookintegration.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Facebook"
        android:id="@+id/txt_facebook"
        android:textSize="20dp"
         />

</LinearLayout>