How to integrate Facebook using Kotlin?


This example demonstrates how to integrate Facebook using Kotlin.

Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project.

Step 2 − In your project, open your_app | Gradle Scripts | build.gradle (Module: app) and add the following compile statement to the dependencies{} section to compile the latest version of the SDK −

implementation 'com.facebook.android:facebook-login:5.15.3'

Step 3 − Add your package name and default activity class name as shown below, click save and continue.

Step 4 − Create a Key hash. Based on your operating system you have to copy the code → Open Android Studio Rarr; Open terminal and paste the code as shown below.

Once you enter the code, it will ask you to enter the keystore password. Enter “android”, it will give you the Key hash. Copy the key hash paste in the Key Hash section in the facebook developer site as shown below.

Click save and continue.

Step 5 − Simply click Next.

Step 6 − Open res/strings.xml and add the following code:

<string name="facebook_app_id">511795909507190</string>
<string name="fb_login_protocol_scheme">fb511795909507190</string>

Step 7 − Add the following code to res/layout/activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<com.facebook.login.widget.LoginButton
xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/loginButton"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_gravity="center_horizontal"
   android:layout_marginTop="30dp"
   android:layout_marginBottom="30dp" />

Step 8 − Add the following code to MainActivity.kt

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.facebook.AccessToken
import com.facebook.CallbackManager
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.facebook.login.widget.LoginButton
@Suppress("DEPRECATION")
class MainActivity : AppCompatActivity() {
   lateinit var callbackManager: CallbackManager
   private val EMAIL = "email"
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
      val loginButton = findViewById<LoginButton>(R.id.loginButton)
      loginButton.setOnClickListener {
         loginButton.setReadPermissions(listOf(EMAIL))
         callbackManager = CallbackManager.Factory.create()
         // If you are using in a fragment, call loginButton.setFragment(this);
         // Callback registration
         // If you are using in a fragment, call loginButton.setFragment(this);
         // Callback registration
         loginButton.registerCallback(callbackManager, object : FacebookCallback<LoginResult?> {
            override fun onSuccess(loginResult: LoginResult?) {
               Log.d("MainActivity", "Facebook token: " + loginResult!!.accessToken.token)
               startActivity(
                  Intent(
                     applicationContext,
                     AuthenticatedActivity::class.java
                  )
               )// App code
            }
            override fun onCancel() { // App code
         }
         override fun onError(exception: FacebookException) { // App code
      }
   })
   callbackManager = CallbackManager.Factory.create()
   LoginManager.getInstance().registerCallback(callbackManager,
   object : FacebookCallback<LoginResult?> {
      override fun onSuccess(loginResult: LoginResult?) { // App code
   }
   override fun onCancel() { // App code
   }
   override fun onError(exception: FacebookException) { // App code
   }
   val accessToken = AccessToken.getCurrentAccessToken()
   accessToken != null && !accessToken.isExpired
   }
   override fun onActivityResult(
      requestCode: Int,
      resultCode: Int,
      data: Intent?
   ) {
      callbackManager.onActivityResult(requestCode, resultCode, data)
      super.onActivityResult(requestCode, resultCode, data)
      callbackManager.onActivityResult(requestCode, resultCode, data)
   }
}

Step 9 − Create a class naming MyApplication.kt which extends Application and add the following −

import android.app.Application
import com.facebook.FacebookSdk
import com.facebook.appevents.AppEventsLogger
@Suppress("DEPRECATION")
class MyApplication : Application() {
   override fun onCreate() {
      super.onCreate()
      FacebookSdk.sdkInitialize(applicationContext)
      AppEventsLogger.activateApp(this)
   }
}

Step 10 − Create a new activity for Logout and add the following code −

LogoutActivty.kt

import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.facebook.AccessToken
import com.facebook.GraphRequest
import com.facebook.HttpMethod
import com.facebook.login.LoginManager
class LogoutActivity : AppCompatActivity() {
   override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.logout_activity)
      val btnLogout = findViewById<Button>(R.id.btnLogout)
      btnLogout.setOnClickListener(View.OnClickListener {
         // Logout
         if (AccessToken.getCurrentAccessToken() != null) {
            GraphRequest(
               AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE,
               GraphRequest.Callback {
                  AccessToken.setCurrentAccessToken(null)
                  LoginManager.getInstance().logOut()
                  finish()
               }
            ).executeAsync()
         }
      })
   }
}

logout_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent">
   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:orientation="vertical">
   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_gravity="center_horizontal"
      android:text="Login success!" />
   <Button
      android:id="@+id/btnLogout"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_margin="20dp"
      android:background="#3c66c4"
      android:text="Logout"
      android:textAllCaps="false"
      android:textColor="@android:color/white" />
   </LinearLayout>
</RelativeLayout>

Step 11 − Add the following code to androidManifest.xml

(Note − You have add the Meta data inside the application)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="app.com.q35">
   <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>
      <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>
      <activity android:name=".LogoutActivity" />
   </application>
</manifest>

Kindly visit https://developers.facebook.com/  to for any clarifications..

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen

Once you click login it will go to the login screen and you have to enter your username and password. Since i have logged it previously, it is asking to continue. Once you click login and if the authentication is successful it will show you logout Activity.

Click here to download the project code.

Updated on: 21-Apr-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements