← Back to list

Facebook Login in Jetpack Compose: A Modern Approach with Facebook SDK

Introduction:

Hemalathassrinivas · 2024-11-14 12:35 · 0 claps · 3.4 min read
#facebook #android-app-development #facebook-login #jetpack-compose #facebook-sdk
Open on Medium ↗
Wiki topics: 📱 · Mobile Development

Facebook Login in Jetpack Compose: A Modern Approach with Facebook SDK

Introduction:

In this article, we will explore how to integrate Facebook login into an Android app using the Facebook SDK with Jetpack Compose. This guide focuses on implementing Facebook authentication while leveraging Jetpack Compose for UI, ViewModel for managing state, and SharedPreferences for session management. You’ll learn how to log in users, handle session tokens, and display user information, all while keeping your app’s architecture clean and organised.

Prerequisites:

Before diving into the implementation, ensure you have the following:

  • Basic Knowledge of Android Development: You should be familiar with Android app development, particularly Jetpack Compose.
  • Facebook Developer Account: You need a Facebook Developer account and a Facebook App ID. You can create a Facebook app in the Facebook developers Account.
  • For a step-by-step guide to create a Facebook Developer account and app, you can follow this guide.
  • Android Studio Setup: Make sure you have Android Studio installed, with a project that uses Jetpack Compose.

Step 1: Setting Up Facebook SDK

  • Set up a new app and retrieve the App ID and other credentials from your Facebook Developer account. You can follow the link provided in the Prerequisites section for a step-by-step guide to creating a Facebook Developer account and app.
  • In your project, open your_app > Gradle Scripts > build.gradle (Project) make sure the following repository is listed
buildscript {
    repositories {
        google()
        mavenCentral()
    }
}
  • Add Dependencies: Explain the required dependencies for Facebook SDK in your build.gradle file:
implementation (libs.facebook.android.sdk)

Step 2: Configure Facebook SDK in the Manifest

<provider android:authorities="com.facebook.app.FacebookContentProvider8324827134279048"
    android:name="com.facebook.FacebookContentProvider"
    android:exported="true" />

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<meta-data android:name="com.facebook.sdk.ClientToken" android:value="@string/facebook_token"/>
<meta-data android:name="com.facebook.sdk.AutoInitEnabled" android:value="true" />

Also, add the necessary permission for internet access:

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

Step 3: Create the Facebook Login Activity

In this step:

  • We initialize Facebook SDK using CallbackManager.
  • A Compose UI is set, which dynamically changes based on whether the user is logged in or not.
  • A Button initiates Facebook login by calling LoginManager.getInstance().logInWithReadPermissions().
class FacebookActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Initialize the Facebook callback manager
        callbackManager = CallbackManager.Factory.create()

        // Set the Compose content
        setContent {
            FacebookLoginScreen()
        }
    }
@Composable
    fun FacebookLoginScreen() {

        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            if (isLoggedIn) {
                Text(text = "Welcome, $userName", style = MaterialTheme.typography.bodyLarge)
                Button(onClick = {/* Handle sign out*/}) {
                    Text("Sign Out")
                }
            } else {
                Button(onClick = { initiateFacebookLogin() }) {
                Text("Login with Facebook")
                  }
            }
        }
    }
fun initiateFacebookLogin() {
        LoginManager.getInstance().logInWithReadPermissions(this, listOf("public_profile"))
        LoginManager.getInstance().registerCallback(callbackManager, object : FacebookCallback<LoginResult> {
            override fun onSuccess(result: LoginResult) {
                lifecycleScope.launch {
                    viewModel.saveAccessToken(result.accessToken)
                }
            }

            override fun onCancel() {
                Toast.makeText(this@FacebookActivity, "Login canceled", Toast.LENGTH_SHORT).show()
            }

            override fun onError(error: FacebookException) {
                Toast.makeText(this@FacebookActivity, "Login failed", Toast.LENGTH_SHORT).show()
            }
        })
    }

Step 4: Managing Login State with ViewModel

class FacebookLoginViewModel(private val sharedPreferences: SharedPreferences) : ViewModel() {

    private val _isLoggedIn = MutableStateFlow(false)
    val isLoggedIn: StateFlow<Boolean> = _isLoggedIn

    private val _userName = MutableStateFlow("")
    val userName: StateFlow<String> = _userName

    init {
        // Check if a valid session is available on initialization
        viewModelScope.launch {
            val token = getSavedAccessToken()
            if (token != null && !token.isExpired) {
                _isLoggedIn.value = true
                fetchUserName(token)
            }
        }
    }

To Save the access token in SharedPreferences

 fun saveAccessToken(token: AccessToken) {
        sharedPreferences.edit()
            .putString("access_token", token.token)
            .putLong("expires_at", token.expires.time)
            .putString("user_id", token.userId)
            .apply()

        _isLoggedIn.value = true
        fetchUserName(token)
    }

    private fun getSavedAccessToken(): AccessToken? {
        val token = sharedPreferences.getString("access_token", null)
        val expiresAt = sharedPreferences.getLong("expires_at", 0)
        val userId = sharedPreferences.getString("user_id", null)
        return if (token != null && userId != null && expiresAt > System.currentTimeMillis()) {
            AccessToken(token, "facebook", userId, setOf("public_profile"), null, null, AccessTokenSource.FACEBOOK_APPLICATION_WEB, Date(expiresAt), null, null, null)
        } else null
    }

Fetch user name using Facebook Graph API

viewModelScope.launch(Dispatchers.IO) {
            try {
                val request = GraphRequest.newMeRequest(token) { jsonObject, _ ->
                    val name = jsonObject?.getString("name") ?: "Unknown"
                    Log.d("FacebookLoginViewModel", "User name fetched: $name")
                    _userName.value = name
                }
                val parameters = Bundle().apply {
                    putString("fields", "id,name,email,picture")
                }
                request.parameters = parameters
                request.executeAsync()
            } catch (e: Exception) {
                Log.e("FacebookLogin", "Error fetching user name: ${e.message}")
            }
        }
fun signOut() {
        LoginManager.getInstance().logOut()
        sharedPreferences.edit().clear().apply()
        _isLoggedIn.value = false
        _userName.value = ""
    }

Here, the FacebookLoginViewModel is responsible for:

  • Checking the login session on initialization.
  • Saving and retrieving the access token from SharedPreferences.
  • Using the Facebook Graph API to fetch the user’s name.
  • Logging the user out and clearing the session.

Step 5: Creating the ViewModel Factory

You will also need a FacebookLoginViewModelFactory to create the ViewModel instance with the required SharedPreferences:

class FacebookLoginViewModelFactory(
    private val sharedPreferences: SharedPreferences
) : ViewModelProvider.Factory {

    @Suppress("UNCHECKED_CAST")
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if (modelClass.isAssignableFrom(FacebookLoginViewModel::class.java)) {
            return FacebookLoginViewModel(sharedPreferences) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")
    }
}

Step 6: Handling Login Callbacks

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

This ensures that Facebook’s login manager processes the login result properly.

Conclusion

With these steps, you’ve successfully implemented Facebook login using Jetpack Compose in Android. This implementation stores and retrieves session data, manages user state with ViewModel, and provides a seamless login experience.

If you found this article helpful, consider sharing it with others or leaving a comment below!


메타데이터
post_id
7062eee33db0
slug
facebook-login-in-jetpack-compose-a-modern-approach-with-facebook-sdk-7062eee33db0
url
https://medium.com/@hemalathassrinivas/facebook-login-in-jetpack-compose-a-modern-approach-with-facebook-sdk-7062eee33db0
canonical_url
https://medium.com/@hemalathassrinivas/facebook-login-in-jetpack-compose-a-modern-approach-with-facebook-sdk-7062eee33db0
author_url
https://medium.com/@hemalathassrinivas
status
ok
fetched_at
2026-07-20 18:33:08