Facebook SDK for Android providing comprehensive integration with Facebook platform features including Login, Sharing, Messenger, App Links, Analytics, and Graph API
—
The Facebook SDK core module provides essential functionality for SDK initialization, configuration, access token management, and Graph API access. This is the foundation that all other Facebook SDK modules depend on.
The Facebook SDK must be initialized before use, typically in your Application class.
object FacebookSdk {
fun sdkInitialize(applicationContext: Context)
fun sdkInitialize(applicationContext: Context, callback: InitializeCallback?)
fun isInitialized(): Boolean
fun fullyInitialize()
fun isFullyInitialized(): Boolean
}
interface InitializeCallback {
fun onInitialized()
}class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
FacebookSdk.sdkInitialize(applicationContext) {
// SDK initialization complete
Log.d("Facebook", "SDK initialized")
}
}
}object FacebookSdk {
// Application configuration
fun getApplicationId(): String
fun setApplicationId(applicationId: String)
fun getApplicationName(): String?
fun setApplicationName(applicationName: String?)
fun getClientToken(): String
fun setClientToken(clientToken: String?)
// Version information
fun getSdkVersion(): String
fun getGraphApiVersion(): String
fun setGraphApiVersion(graphApiVersion: String)
// Context and execution
fun getApplicationContext(): Context
fun getExecutor(): Executor
fun setExecutor(executor: Executor)
// Debugging and logging
fun isDebugEnabled(): Boolean
fun setIsDebugEnabled(enabled: Boolean)
fun getLoggingBehaviors(): Set<LoggingBehavior>
fun addLoggingBehavior(behavior: LoggingBehavior)
fun removeLoggingBehavior(behavior: LoggingBehavior)
fun clearLoggingBehaviors()
fun isLoggingBehaviorEnabled(behavior: LoggingBehavior): Boolean
}
enum class LoggingBehavior {
REQUESTS,
INCLUDE_ACCESS_TOKENS,
INCLUDE_RAW_RESPONSES,
CACHE,
APP_EVENTS,
DEVELOPER_ERRORS,
GRAPH_API_DEBUG_WARNING,
GRAPH_API_DEBUG_INFO
}Access tokens are central to Facebook API interactions, representing user authentication and permissions.
class AccessToken(
accessToken: String,
applicationId: String,
userId: String,
permissions: Collection<String?>?,
declinedPermissions: Collection<String?>?,
expiredPermissions: Collection<String?>?,
accessTokenSource: AccessTokenSource?,
expirationTime: Date?,
lastRefreshTime: Date?,
dataAccessExpirationTime: Date?,
graphDomain: String? = "facebook"
) {
val token: String
val applicationId: String
val userId: String
val permissions: Set<String?>
val declinedPermissions: Set<String?>
val expiredPermissions: Set<String?>
val expires: Date
val lastRefresh: Date
val dataAccessExpirationTime: Date
val source: AccessTokenSource
val graphDomain: String?
// Token status
val isExpired: Boolean
val isDataAccessExpired: Boolean
val isInstagramToken: Boolean
companion object {
// Current token management
fun getCurrentAccessToken(): AccessToken?
fun setCurrentAccessToken(accessToken: AccessToken?)
fun isCurrentAccessTokenActive(): Boolean
fun isDataAccessActive(): Boolean
fun isLoggedInWithInstagram(): Boolean
fun expireCurrentAccessToken()
// Token refresh
fun refreshCurrentAccessTokenAsync()
fun refreshCurrentAccessTokenAsync(callback: AccessTokenRefreshCallback?)
// Token creation
fun createFromNativeLinkingIntent(
intent: Intent,
applicationId: String,
accessTokenCallback: AccessTokenCreationCallback
)
}
}
enum class AccessTokenSource {
FACEBOOK_APPLICATION_WEB,
FACEBOOK_APPLICATION_NATIVE,
FACEBOOK_APPLICATION_SERVICE,
WEB_VIEW,
CHROME_CUSTOM_TAB,
INSTAGRAM_APPLICATION_WEB,
INSTAGRAM_CUSTOM_CHROME_TAB,
INSTAGRAM_WEB_VIEW
}
interface AccessTokenRefreshCallback {
fun OnTokenRefreshed(accessToken: AccessToken?)
fun OnTokenRefreshFailed(exception: FacebookException?)
}
interface AccessTokenCreationCallback {
fun onSuccess(token: AccessToken?)
fun onError(error: FacebookException?)
}// Check if user is logged in
if (AccessToken.isCurrentAccessTokenActive()) {
val currentToken = AccessToken.getCurrentAccessToken()
val userId = currentToken?.userId
val permissions = currentToken?.permissions
// Use the token for API calls
makeGraphRequest(currentToken)
} else {
// User needs to log in
initiateLogin()
}
// Refresh current token
AccessToken.refreshCurrentAccessTokenAsync { accessToken ->
if (accessToken != null) {
// Token refreshed successfully
Log.d("Facebook", "Token refreshed for user: ${accessToken.userId}")
} else {
// Token refresh failed
Log.e("Facebook", "Failed to refresh token")
}
}class Profile(
id: String?,
firstName: String?,
middleName: String?,
lastName: String?,
name: String?,
linkUri: Uri?,
pictureUri: Uri?
) {
val id: String?
val firstName: String?
val middleName: String?
val lastName: String?
val name: String?
val linkUri: Uri?
val pictureUri: Uri?
companion object {
fun getCurrentProfile(): Profile?
fun setCurrentProfile(profile: Profile?)
fun fetchProfileForCurrentAccessToken()
}
}
abstract class ProfileTracker {
val isTracking: Boolean
fun startTracking()
fun stopTracking()
protected abstract fun onCurrentProfileChanged(
oldProfile: Profile?,
currentProfile: Profile?
)
}For apps using OpenID Connect authentication:
class AuthenticationToken(
token: String,
nonce: String,
graphDomain: String
) {
val token: String
val nonce: String
val graphDomain: String
val header: AuthenticationTokenHeader
val claims: AuthenticationTokenClaims
companion object {
fun getCurrentAuthenticationToken(): AuthenticationToken?
fun setCurrentAuthenticationToken(token: AuthenticationToken?)
}
}
class AuthenticationTokenClaims(
encodedClaims: String,
expectedNonce: String
) {
val jti: String?
val iss: String?
val aud: String?
val nonce: String?
val exp: Long
val iat: Long
val sub: String?
val name: String?
val givenName: String?
val middleName: String?
val familyName: String?
val email: String?
val picture: String?
val userFriends: List<String>?
val userBirthday: String?
val userAgeRange: Map<String, Int>?
val userHometown: Map<String, String>?
val userLocation: Map<String, String>?
val userGender: String?
val userLink: String?
}
class AuthenticationTokenHeader(encodedHeader: String) {
val alg: String?
val typ: String?
val kid: String?
}open class FacebookException(message: String?) : RuntimeException(message)
class FacebookSdkNotInitializedException(message: String?) : FacebookException(message)
class FacebookAuthorizationException(message: String?) : FacebookException(message)
class FacebookOperationCanceledException(message: String?) : FacebookException(message)
class FacebookServiceException(
error: FacebookRequestError,
errorMessage: String?
) : FacebookException(errorMessage)
class FacebookGraphResponseException(
response: GraphResponse,
message: String?
) : FacebookException(message) {
val graphResponse: GraphResponse
}
class FacebookRequestError(
requestStatusCode: Int,
errorCode: Int,
errorType: String?,
errorMessage: String?
) {
val requestStatusCode: Int
val errorCode: Int
val errorType: String?
val errorMessage: String?
val errorUserMessage: String?
val errorUserTitle: String?
val requestResult: JSONObject?
enum class Category {
LOGIN_RECOVERABLE,
OTHER,
TRANSIENT
}
val category: Category
}interface CallbackManager {
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean
object Factory {
fun create(): CallbackManager
}
}
interface FacebookCallback<T> {
fun onSuccess(result: T)
fun onCancel()
fun onError(error: FacebookException)
}class MainActivity : AppCompatActivity() {
private lateinit var callbackManager: CallbackManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
callbackManager = CallbackManager.Factory.create()
// Register callbacks for various Facebook operations
LoginManager.getInstance().registerCallback(callbackManager, loginCallback)
ShareDialog(this).registerCallback(callbackManager, shareCallback)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
// This delegates to all registered Facebook callbacks
callbackManager.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
}
}object UserSettingsManager {
fun getAutoInitEnabled(): Boolean
fun setAutoInitEnabled(enabled: Boolean)
fun getAutoLogAppEventsEnabled(): Boolean
fun setAutoLogAppEventsEnabled(enabled: Boolean)
fun getAdvertiserIDCollectionEnabled(): Boolean
fun setAdvertiserIDCollectionEnabled(enabled: Boolean)
fun getCodelessSetupEnabled(): Boolean
fun getMonitorEnabled(): Boolean
fun setMonitorEnabled(enabled: Boolean)
}Install with Tessl CLI
npx tessl i tessl/maven-com-facebook-android--facebook-android-sdk