Facebook Integration: How to login with facebook in Android using Kotlin code

Last updated Dec 19, 2021


In this android example tutorial we will see integrate Facebook sdk and  login with facebook in android using Kotlin Programming Language.

Implementation:

Step 1:
Create a new project in Android Studio, go to File > New Project and fill all required details to create a new project.
To work with Facebook sdk we need to create an application in Facebook developer account and get the api keys.
 

Step 2: Go to facebook developers console and login/signup with  credentials.

https://developers.facebook.com/

Click on Login/SignUp which is available on the right side of the screen, fill your credentails and enter in your dashboard.


Step 3: Click on Create App 

FaceBook developer account

 

 Select an app type > Business and then Next.

Enter the Display name and click Create App.
 May be show re-enter password window, enter the password and continue.

FaceBook developer account 2

On your window  you will see the option of Facebook Login and click on SetUP.

Select Android.

After this you will see the window for
Download the Facebook SDK for Android > Click on Next.
Import the Facebook SDK > Click on Next.
Tell Us about Your Android Project > Enter your package name : "com.example.yourappname" and Default Activity Class Name : "com.example.yourappname.MainActivity"
Enter Save then Continue.

 

Now we need to add hashkeys to verify our application, to create HashKey we need to use below code

Step 2: We will get HashKey from Android Project by adding following code in MainActivity.

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        printHashKey()
    }
    fun printHashKey(){
        try {
            val info = packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
            for (signature in info.signatures) {
                val md = MessageDigest.getInstance("SHA")
                md.update(signature.toByteArray())
                Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT))
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        }
    }

}

After run the app you will get a Key in logcat.

Facebook SDK login

 

Add Your Development and Release Key Hashes > Enter your hashKey in Key Hashes Box and click Save and then CONTINUE.
Enable Single Sign On for Your App > Enable Single sign on Status from No To Yes > Enter Save and Next.

 

We are done with creating app at facebook developer account, now we need to configure our android application.

 

Step 4:  Copy the the key strings which you get from facebook dashboard and paste in strings.xml file

<string name="facebook_app_id">Your facebook app id</string>
<string name="fb_login_protocol_scheme">Your protocol</string>

 

 

Step 5: Add the facebook sdk dependency to build.gradle(app) inside dependencies element.

implementation 'com.facebook.android:facebook-android-sdk:12.0.0'

 

Step 6: Add the Internet permission into AndroidManifest.xml file

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


 

Step 7: Add the following code  in AndroidManifest.xml file inside application element.

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

 

Now we will add facebook default login button into our xml file, this will gives the default facebook login button to handle login feature

Step 8: Open activity_main.xml file and ad the following code inside constraint layout.

      <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

 

Now let's add facebook login functionality in our example activity

Step 9: After adding open MainActivity.xml file and add the code.

private const val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {

    private lateinit var callbackManager: CallbackManager
    private lateinit var loginButton: LoginButton


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        //init
        loginButton = findViewById(R.id.login_button)
        callbackManager = CallbackManager.Factory.create()
        loginButton.setPermissions(listOf("email", "user_birthday"))

        //login callback
        loginButton.registerCallback(callbackManager, object : FacebookCallback {

            override fun onSuccess(result: LoginResult) {
                val userId = result.accessToken.userId
                Log.d(TAG, "onSuccess: userId $userId")

                val bundle = Bundle()
                bundle.putString("fields", "id, email, first_name, last_name, gender,age_range")


                //Graph API to access the data of user's facebook account
                val request = GraphRequest.newMeRequest(
                    result.accessToken
                ) { fbObject, response ->
                    Log.v("Login Success", response.toString())

                    //For safety measure enclose the request with try and catch
                    try {

                        Log.d(TAG, "onSuccess: fbObject $fbObject")

                        val firstName = fbObject?.getString("first_name")
                        val lastName = fbObject?.getString("last_name")
//                        val gender = fbObject?.getString("gender")
                        val email = fbObject?.getString("email")

                        Log.d(TAG, "onSuccess: firstName $firstName")
                        Log.d(TAG, "onSuccess: lastName $lastName")
//                        Log.d(TAG, "onSuccess: gender $gender")
                        Log.d(TAG, "onSuccess: email $email")

                    } //If no data has been retrieve throw some error
                    catch (e: JSONException) {

                    }

                }
                //Set the bundle's data as Graph's object data
                request.parameters(bundle)

                //Execute this Graph request asynchronously
                request.executeAsync()

            }

            override fun onCancel() {
                Log.d(TAG, "onCancel: called")
            }

            override fun onError(error: FacebookException) {
                Log.d(TAG, "onError: called")
            }
        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)

    }

}

private fun GraphRequest.parameters(bundle: Bundle) {

}

 

Step 10: Now run the app you will see the output as below:
OUTPUT:

FaceBook Login and logout android

 

FaceBook Login and logout kotlin code

 

Complete Source Code of Facebook Login with Example:
 

  • activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
 

MainActivity.kt file

import android.content.ContentValues.TAG
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.facebook.*
import com.facebook.login.LoginResult
import com.facebook.login.widget.LoginButton
import org.json.JSONException

private const val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {

    private lateinit var callbackManager: CallbackManager
    private lateinit var loginButton: LoginButton


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        //init
        loginButton = findViewById(R.id.login_button)
        callbackManager = CallbackManager.Factory.create()
        loginButton.setPermissions(listOf("email", "user_birthday"))

        //login callback
        loginButton.registerCallback(callbackManager, object : FacebookCallback {

            override fun onSuccess(result: LoginResult) {
                val userId = result.accessToken.userId
                Log.d(TAG, "onSuccess: userId $userId")

                val bundle = Bundle()
                bundle.putString("fields", "id, email, first_name, last_name, gender,age_range")


                //Graph API to access the data of user's facebook account
                val request = GraphRequest.newMeRequest(
                    result.accessToken
                ) { fbObject, response ->
                    Log.v("Login Success", response.toString())

                    //For safety measure enclose the request with try and catch
                    try {

                        Log.d(TAG, "onSuccess: fbObject $fbObject")

                        val firstName = fbObject?.getString("first_name")
                        val lastName = fbObject?.getString("last_name")
//                        val gender = fbObject?.getString("gender")
                        val email = fbObject?.getString("email")

                        Log.d(TAG, "onSuccess: firstName $firstName")
                        Log.d(TAG, "onSuccess: lastName $lastName")
//                        Log.d(TAG, "onSuccess: gender $gender")
                        Log.d(TAG, "onSuccess: email $email")

                    } //If no data has been retrieve throw some error
                    catch (e: JSONException) {

                    }

                }
                //Set the bundle's data as Graph's object data
                request.parameters(bundle)

                //Execute this Graph request asynchronously
                request.executeAsync()

            }

            override fun onCancel() {
                Log.d(TAG, "onCancel: called")
            }

            override fun onError(error: FacebookException) {
                Log.d(TAG, "onError: called")
            }
        })
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        callbackManager.onActivityResult(requestCode, resultCode, data)
        super.onActivityResult(requestCode, resultCode, data)

    }

}

private fun GraphRequest.parameters(bundle: Bundle) {

}

 

AndroidManifest.xml file


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="Your Package Name">

    <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/Theme.FacebookLogin">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

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

</manifest>

 

strings.xml file

<resources>
    <string name="app_name">FacebookLogin</string>
    <string name="facebook_app_id">Your facebook app id</string>
    <string name="fb_login_protocol_scheme">Your fb login protocol</string>
</resources>

 

 

build.gradle(app) file

plugins {
    id 'com.android.application'
    id 'kotlin-android'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "Your package name"
        minSdk 21
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.0'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.2'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'

    implementation 'com.facebook.android:facebook-android-sdk:12.0.0'
}

 

Conclusion: All we have covered how to integrate facebook sdk in android and  login with facebook in android app using Kotlin Language.


Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

785 Views

Subscribe For Daily Updates

Flutter Questions
Android Questions