0
# SDK Core & Authentication
1
2
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.
3
4
## SDK Initialization
5
6
The Facebook SDK must be initialized before use, typically in your Application class.
7
8
```kotlin { .api }
9
object FacebookSdk {
10
fun sdkInitialize(applicationContext: Context)
11
fun sdkInitialize(applicationContext: Context, callback: InitializeCallback?)
12
fun isInitialized(): Boolean
13
fun fullyInitialize()
14
fun isFullyInitialized(): Boolean
15
}
16
17
interface InitializeCallback {
18
fun onInitialized()
19
}
20
```
21
22
### Usage Example
23
24
```kotlin
25
class MyApplication : Application() {
26
override fun onCreate() {
27
super.onCreate()
28
FacebookSdk.sdkInitialize(applicationContext) {
29
// SDK initialization complete
30
Log.d("Facebook", "SDK initialized")
31
}
32
}
33
}
34
```
35
36
## SDK Configuration
37
38
```kotlin { .api }
39
object FacebookSdk {
40
// Application configuration
41
fun getApplicationId(): String
42
fun setApplicationId(applicationId: String)
43
fun getApplicationName(): String?
44
fun setApplicationName(applicationName: String?)
45
fun getClientToken(): String
46
fun setClientToken(clientToken: String?)
47
48
// Version information
49
fun getSdkVersion(): String
50
fun getGraphApiVersion(): String
51
fun setGraphApiVersion(graphApiVersion: String)
52
53
// Context and execution
54
fun getApplicationContext(): Context
55
fun getExecutor(): Executor
56
fun setExecutor(executor: Executor)
57
58
// Debugging and logging
59
fun isDebugEnabled(): Boolean
60
fun setIsDebugEnabled(enabled: Boolean)
61
fun getLoggingBehaviors(): Set<LoggingBehavior>
62
fun addLoggingBehavior(behavior: LoggingBehavior)
63
fun removeLoggingBehavior(behavior: LoggingBehavior)
64
fun clearLoggingBehaviors()
65
fun isLoggingBehaviorEnabled(behavior: LoggingBehavior): Boolean
66
}
67
68
enum class LoggingBehavior {
69
REQUESTS,
70
INCLUDE_ACCESS_TOKENS,
71
INCLUDE_RAW_RESPONSES,
72
CACHE,
73
APP_EVENTS,
74
DEVELOPER_ERRORS,
75
GRAPH_API_DEBUG_WARNING,
76
GRAPH_API_DEBUG_INFO
77
}
78
```
79
80
## Access Token Management
81
82
Access tokens are central to Facebook API interactions, representing user authentication and permissions.
83
84
```kotlin { .api }
85
class AccessToken(
86
accessToken: String,
87
applicationId: String,
88
userId: String,
89
permissions: Collection<String?>?,
90
declinedPermissions: Collection<String?>?,
91
expiredPermissions: Collection<String?>?,
92
accessTokenSource: AccessTokenSource?,
93
expirationTime: Date?,
94
lastRefreshTime: Date?,
95
dataAccessExpirationTime: Date?,
96
graphDomain: String? = "facebook"
97
) {
98
val token: String
99
val applicationId: String
100
val userId: String
101
val permissions: Set<String?>
102
val declinedPermissions: Set<String?>
103
val expiredPermissions: Set<String?>
104
val expires: Date
105
val lastRefresh: Date
106
val dataAccessExpirationTime: Date
107
val source: AccessTokenSource
108
val graphDomain: String?
109
110
// Token status
111
val isExpired: Boolean
112
val isDataAccessExpired: Boolean
113
val isInstagramToken: Boolean
114
115
companion object {
116
// Current token management
117
fun getCurrentAccessToken(): AccessToken?
118
fun setCurrentAccessToken(accessToken: AccessToken?)
119
fun isCurrentAccessTokenActive(): Boolean
120
fun isDataAccessActive(): Boolean
121
fun isLoggedInWithInstagram(): Boolean
122
fun expireCurrentAccessToken()
123
124
// Token refresh
125
fun refreshCurrentAccessTokenAsync()
126
fun refreshCurrentAccessTokenAsync(callback: AccessTokenRefreshCallback?)
127
128
// Token creation
129
fun createFromNativeLinkingIntent(
130
intent: Intent,
131
applicationId: String,
132
accessTokenCallback: AccessTokenCreationCallback
133
)
134
}
135
}
136
137
enum class AccessTokenSource {
138
FACEBOOK_APPLICATION_WEB,
139
FACEBOOK_APPLICATION_NATIVE,
140
FACEBOOK_APPLICATION_SERVICE,
141
WEB_VIEW,
142
CHROME_CUSTOM_TAB,
143
INSTAGRAM_APPLICATION_WEB,
144
INSTAGRAM_CUSTOM_CHROME_TAB,
145
INSTAGRAM_WEB_VIEW
146
}
147
148
interface AccessTokenRefreshCallback {
149
fun OnTokenRefreshed(accessToken: AccessToken?)
150
fun OnTokenRefreshFailed(exception: FacebookException?)
151
}
152
153
interface AccessTokenCreationCallback {
154
fun onSuccess(token: AccessToken?)
155
fun onError(error: FacebookException?)
156
}
157
```
158
159
### Access Token Usage Example
160
161
```kotlin
162
// Check if user is logged in
163
if (AccessToken.isCurrentAccessTokenActive()) {
164
val currentToken = AccessToken.getCurrentAccessToken()
165
val userId = currentToken?.userId
166
val permissions = currentToken?.permissions
167
168
// Use the token for API calls
169
makeGraphRequest(currentToken)
170
} else {
171
// User needs to log in
172
initiateLogin()
173
}
174
175
// Refresh current token
176
AccessToken.refreshCurrentAccessTokenAsync { accessToken ->
177
if (accessToken != null) {
178
// Token refreshed successfully
179
Log.d("Facebook", "Token refreshed for user: ${accessToken.userId}")
180
} else {
181
// Token refresh failed
182
Log.e("Facebook", "Failed to refresh token")
183
}
184
}
185
```
186
187
## User Profile Management
188
189
```kotlin { .api }
190
class Profile(
191
id: String?,
192
firstName: String?,
193
middleName: String?,
194
lastName: String?,
195
name: String?,
196
linkUri: Uri?,
197
pictureUri: Uri?
198
) {
199
val id: String?
200
val firstName: String?
201
val middleName: String?
202
val lastName: String?
203
val name: String?
204
val linkUri: Uri?
205
val pictureUri: Uri?
206
207
companion object {
208
fun getCurrentProfile(): Profile?
209
fun setCurrentProfile(profile: Profile?)
210
fun fetchProfileForCurrentAccessToken()
211
}
212
}
213
214
abstract class ProfileTracker {
215
val isTracking: Boolean
216
217
fun startTracking()
218
fun stopTracking()
219
220
protected abstract fun onCurrentProfileChanged(
221
oldProfile: Profile?,
222
currentProfile: Profile?
223
)
224
}
225
```
226
227
## Authentication Tokens (OpenID Connect)
228
229
For apps using OpenID Connect authentication:
230
231
```kotlin { .api }
232
class AuthenticationToken(
233
token: String,
234
nonce: String,
235
graphDomain: String
236
) {
237
val token: String
238
val nonce: String
239
val graphDomain: String
240
val header: AuthenticationTokenHeader
241
val claims: AuthenticationTokenClaims
242
243
companion object {
244
fun getCurrentAuthenticationToken(): AuthenticationToken?
245
fun setCurrentAuthenticationToken(token: AuthenticationToken?)
246
}
247
}
248
249
class AuthenticationTokenClaims(
250
encodedClaims: String,
251
expectedNonce: String
252
) {
253
val jti: String?
254
val iss: String?
255
val aud: String?
256
val nonce: String?
257
val exp: Long
258
val iat: Long
259
val sub: String?
260
val name: String?
261
val givenName: String?
262
val middleName: String?
263
val familyName: String?
264
val email: String?
265
val picture: String?
266
val userFriends: List<String>?
267
val userBirthday: String?
268
val userAgeRange: Map<String, Int>?
269
val userHometown: Map<String, String>?
270
val userLocation: Map<String, String>?
271
val userGender: String?
272
val userLink: String?
273
}
274
275
class AuthenticationTokenHeader(encodedHeader: String) {
276
val alg: String?
277
val typ: String?
278
val kid: String?
279
}
280
```
281
282
## Exception Handling
283
284
```kotlin { .api }
285
open class FacebookException(message: String?) : RuntimeException(message)
286
287
class FacebookSdkNotInitializedException(message: String?) : FacebookException(message)
288
289
class FacebookAuthorizationException(message: String?) : FacebookException(message)
290
291
class FacebookOperationCanceledException(message: String?) : FacebookException(message)
292
293
class FacebookServiceException(
294
error: FacebookRequestError,
295
errorMessage: String?
296
) : FacebookException(errorMessage)
297
298
class FacebookGraphResponseException(
299
response: GraphResponse,
300
message: String?
301
) : FacebookException(message) {
302
val graphResponse: GraphResponse
303
}
304
305
class FacebookRequestError(
306
requestStatusCode: Int,
307
errorCode: Int,
308
errorType: String?,
309
errorMessage: String?
310
) {
311
val requestStatusCode: Int
312
val errorCode: Int
313
val errorType: String?
314
val errorMessage: String?
315
val errorUserMessage: String?
316
val errorUserTitle: String?
317
val requestResult: JSONObject?
318
319
enum class Category {
320
LOGIN_RECOVERABLE,
321
OTHER,
322
TRANSIENT
323
}
324
325
val category: Category
326
}
327
```
328
329
## Callback Management
330
331
```kotlin { .api }
332
interface CallbackManager {
333
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean
334
335
object Factory {
336
fun create(): CallbackManager
337
}
338
}
339
340
interface FacebookCallback<T> {
341
fun onSuccess(result: T)
342
fun onCancel()
343
fun onError(error: FacebookException)
344
}
345
```
346
347
### Example: Handling Activity Results
348
349
```kotlin
350
class MainActivity : AppCompatActivity() {
351
private lateinit var callbackManager: CallbackManager
352
353
override fun onCreate(savedInstanceState: Bundle?) {
354
super.onCreate(savedInstanceState)
355
callbackManager = CallbackManager.Factory.create()
356
357
// Register callbacks for various Facebook operations
358
LoginManager.getInstance().registerCallback(callbackManager, loginCallback)
359
ShareDialog(this).registerCallback(callbackManager, shareCallback)
360
}
361
362
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
363
// This delegates to all registered Facebook callbacks
364
callbackManager.onActivityResult(requestCode, resultCode, data)
365
super.onActivityResult(requestCode, resultCode, data)
366
}
367
}
368
```
369
370
## User Settings Management
371
372
```kotlin { .api }
373
object UserSettingsManager {
374
fun getAutoInitEnabled(): Boolean
375
fun setAutoInitEnabled(enabled: Boolean)
376
fun getAutoLogAppEventsEnabled(): Boolean
377
fun setAutoLogAppEventsEnabled(enabled: Boolean)
378
fun getAdvertiserIDCollectionEnabled(): Boolean
379
fun setAdvertiserIDCollectionEnabled(enabled: Boolean)
380
fun getCodelessSetupEnabled(): Boolean
381
fun getMonitorEnabled(): Boolean
382
fun setMonitorEnabled(enabled: Boolean)
383
}
384
```