0
# Facebook Android SDK
1
2
The Facebook Android SDK is a comprehensive library that enables Android developers to integrate Facebook platform features into their applications. This multi-module SDK provides modular access to core Facebook services including user authentication through Facebook Login, content sharing capabilities, Messenger integration for rich messaging experiences, App Links for deep linking between apps, advanced analytics and event tracking, and full Graph API access for Facebook data interaction.
3
4
## Package Information
5
6
- **Package Name**: com.facebook.android:facebook-android-sdk
7
- **Package Type**: maven
8
- **Language**: Kotlin/Java
9
- **Installation**: Add to `build.gradle`: `implementation 'com.facebook.android:facebook-android-sdk:18.0.3'`
10
11
## Core Imports
12
13
```kotlin
14
import com.facebook.FacebookSdk
15
import com.facebook.AccessToken
16
import com.facebook.AccessTokenSource
17
import com.facebook.GraphRequest
18
import com.facebook.GraphResponse
19
import com.facebook.FacebookCallback
20
import com.facebook.FacebookException
21
import com.facebook.CallbackManager
22
import com.facebook.LoginStatusCallback
23
import com.facebook.login.LoginManager
24
import com.facebook.login.LoginResult
25
import com.facebook.login.LoginBehavior
26
import com.facebook.login.DefaultAudience
27
import com.facebook.login.LoginTargetApp
28
import com.facebook.login.LoginConfiguration
29
import com.facebook.share.ShareApi
30
import com.facebook.appevents.AppEventsLogger
31
import android.content.Context
32
import android.content.Intent
33
import android.os.Bundle
34
import androidx.activity.ComponentActivity
35
import androidx.activity.result.ActivityResultRegistryOwner
36
import androidx.fragment.app.Fragment
37
import java.util.Date
38
import java.util.concurrent.Executor
39
import java.io.File
40
```
41
42
## Basic Usage
43
44
```kotlin
45
// Initialize SDK (usually in Application.onCreate())
46
class MyApplication : Application() {
47
override fun onCreate() {
48
super.onCreate()
49
FacebookSdk.sdkInitialize(applicationContext)
50
}
51
}
52
53
// Basic login flow
54
class MainActivity : AppCompatActivity() {
55
private lateinit var callbackManager: CallbackManager
56
57
override fun onCreate(savedInstanceState: Bundle?) {
58
super.onCreate(savedInstanceState)
59
60
callbackManager = CallbackManager.Factory.create()
61
62
// Login with permissions
63
LoginManager.getInstance().logInWithReadPermissions(
64
this,
65
listOf("email", "public_profile")
66
)
67
68
// Register callback
69
LoginManager.getInstance().registerCallback(callbackManager,
70
object : FacebookCallback<LoginResult> {
71
override fun onSuccess(result: LoginResult) {
72
val accessToken = result.accessToken
73
// Handle successful login
74
}
75
override fun onCancel() { /* Handle cancellation */ }
76
override fun onError(error: FacebookException) { /* Handle error */ }
77
})
78
}
79
80
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
81
callbackManager.onActivityResult(requestCode, resultCode, data)
82
super.onActivityResult(requestCode, resultCode, data)
83
}
84
}
85
```
86
87
## Architecture
88
89
The Facebook Android SDK is built around several key components:
90
91
- **Core Module**: Foundation SDK functionality including initialization, authentication, Graph API access, and error handling
92
- **Login Module**: Comprehensive authentication system with multiple login methods, UI components, and session management
93
- **Share Module**: Content sharing capabilities including links, photos, videos, and Open Graph stories
94
- **App Links Module**: Deep linking functionality for seamless app-to-app navigation
95
- **Messenger Module**: Direct integration with Messenger for rich messaging experiences
96
- **Gaming Services Module**: Gaming-specific features including tournaments, contexts, and social gaming features
97
- **Bolts Framework**: Asynchronous task management and execution utilities
98
99
## Capabilities
100
101
### SDK Core & Authentication
102
103
Essential SDK functionality including initialization, configuration, access token management, and Graph API access. This is the foundation that all other modules depend on.
104
105
```kotlin { .api }
106
object FacebookSdk {
107
fun sdkInitialize(applicationContext: Context)
108
fun sdkInitialize(applicationContext: Context, callback: InitializeCallback?)
109
fun isInitialized(): Boolean
110
fun getApplicationId(): String
111
fun setApplicationId(applicationId: String)
112
fun getApplicationName(): String?
113
fun setApplicationName(applicationName: String?)
114
fun getClientToken(): String
115
fun setClientToken(clientToken: String?)
116
fun getApplicationContext(): Context
117
fun getSdkVersion(): String
118
fun getGraphApiVersion(): String
119
fun setGraphApiVersion(graphApiVersion: String)
120
fun getAutoInitEnabled(): Boolean
121
fun setAutoInitEnabled(flag: Boolean)
122
fun getAutoLogAppEventsEnabled(): Boolean
123
fun setAutoLogAppEventsEnabled(flag: Boolean)
124
fun isDebugEnabled(): Boolean
125
fun setIsDebugEnabled(enabled: Boolean)
126
fun getLimitEventAndDataUsage(context: Context): Boolean
127
fun setLimitEventAndDataUsage(context: Context, limitEventUsage: Boolean)
128
fun getExecutor(): Executor
129
fun setExecutor(executor: Executor)
130
fun getGraphDomain(): String
131
fun getFacebookDomain(): String
132
fun setFacebookDomain(facebookDomain: String)
133
fun getCacheDir(): File?
134
fun setCacheDir(cacheDir: File)
135
136
fun interface InitializeCallback {
137
fun onInitialized()
138
}
139
}
140
141
class AccessToken(
142
accessToken: String,
143
applicationId: String,
144
userId: String,
145
permissions: Collection<String?>?,
146
declinedPermissions: Collection<String?>?,
147
expiredPermissions: Collection<String?>?,
148
accessTokenSource: AccessTokenSource?,
149
expirationTime: Date?,
150
lastRefreshTime: Date?,
151
dataAccessExpirationTime: Date?,
152
graphDomain: String? = "facebook"
153
) {
154
val token: String
155
val userId: String
156
val applicationId: String
157
val permissions: Set<String?>
158
val declinedPermissions: Set<String?>
159
val expiredPermissions: Set<String?>
160
val expires: Date
161
val lastRefresh: Date
162
val dataAccessExpirationTime: Date
163
val graphDomain: String?
164
val source: AccessTokenSource
165
val isExpired: Boolean
166
val isDataAccessExpired: Boolean
167
val isInstagramToken: Boolean
168
169
interface AccessTokenRefreshCallback {
170
fun OnTokenRefreshed(accessToken: AccessToken?)
171
fun OnTokenRefreshFailed(exception: FacebookException?)
172
}
173
174
interface AccessTokenCreationCallback {
175
fun onSuccess(token: AccessToken?)
176
fun onError(error: FacebookException?)
177
}
178
179
companion object {
180
fun getCurrentAccessToken(): AccessToken?
181
fun setCurrentAccessToken(accessToken: AccessToken?)
182
fun isCurrentAccessTokenActive(): Boolean
183
fun isDataAccessActive(): Boolean
184
fun isLoggedInWithInstagram(): Boolean
185
fun expireCurrentAccessToken()
186
fun refreshCurrentAccessTokenAsync()
187
fun refreshCurrentAccessTokenAsync(callback: AccessTokenRefreshCallback?)
188
fun createFromNativeLinkingIntent(
189
intent: Intent,
190
applicationId: String,
191
accessTokenCallback: AccessTokenCreationCallback
192
)
193
}
194
}
195
```
196
197
[SDK Core & Authentication](./core-authentication.md)
198
199
### Facebook Login
200
201
Comprehensive user authentication system with multiple login methods, customizable UI components, and robust session management. Supports various login behaviors and permission handling.
202
203
```kotlin { .api }
204
class LoginManager {
205
var loginBehavior: LoginBehavior
206
var defaultAudience: DefaultAudience
207
var authType: String
208
var loginTargetApp: LoginTargetApp
209
var isFamilyLogin: Boolean
210
var shouldSkipAccountDeduplication: Boolean
211
212
companion object {
213
fun getInstance(): LoginManager
214
}
215
216
// Basic login methods
217
fun logIn(activity: Activity, permissions: Collection<String>?)
218
fun logIn(fragment: Fragment, permissions: Collection<String>?)
219
fun logIn(activity: Activity, permissions: Collection<String>?, loggerID: String?)
220
fun logIn(fragment: Fragment, permissions: Collection<String>?, loggerID: String?)
221
222
// Read permissions login
223
fun logInWithReadPermissions(activity: Activity, permissions: Collection<String>?)
224
fun logInWithReadPermissions(fragment: Fragment, callbackManager: CallbackManager, permissions: Collection<String>)
225
fun logInWithReadPermissions(activityResultRegistryOwner: ActivityResultRegistryOwner, callbackManager: CallbackManager, permissions: Collection<String>)
226
227
// Publish permissions login
228
fun logInWithPublishPermissions(activity: Activity, permissions: Collection<String>?)
229
fun logInWithPublishPermissions(fragment: Fragment, callbackManager: CallbackManager, permissions: Collection<String>)
230
fun logInWithPublishPermissions(activityResultRegistryOwner: ActivityResultRegistryOwner, callbackManager: CallbackManager, permissions: Collection<String>)
231
232
// Configuration login
233
fun logInWithConfiguration(fragment: Fragment, loginConfig: LoginConfiguration)
234
fun loginWithConfiguration(activity: Activity, loginConfig: LoginConfiguration)
235
236
// Login status and reauthorization
237
fun retrieveLoginStatus(context: Context, responseCallback: LoginStatusCallback)
238
fun retrieveLoginStatus(context: Context, toastDurationMs: Long, responseCallback: LoginStatusCallback)
239
fun reauthorizeDataAccess(activity: Activity)
240
fun reauthorizeDataAccess(fragment: Fragment)
241
242
// Error resolution
243
fun resolveError(activity: Activity, response: GraphResponse)
244
fun resolveError(fragment: Fragment, callbackManager: CallbackManager, response: GraphResponse)
245
fun resolveError(activityResultRegistryOwner: ActivityResultRegistryOwner, callbackManager: CallbackManager, response: GraphResponse)
246
247
// Configuration setters
248
fun setLoginBehavior(loginBehavior: LoginBehavior): LoginManager
249
fun setLoginTargetApp(targetApp: LoginTargetApp): LoginManager
250
fun setDefaultAudience(defaultAudience: DefaultAudience): LoginManager
251
fun setAuthType(authType: String): LoginManager
252
fun setMessengerPageId(messengerPageId: String?): LoginManager
253
fun setResetMessengerState(resetMessengerState: Boolean): LoginManager
254
fun setFamilyLogin(isFamilyLogin: Boolean): LoginManager
255
fun setShouldSkipAccountDeduplication(shouldSkipAccountDeduplication: Boolean): LoginManager
256
257
// Callback management
258
fun registerCallback(callbackManager: CallbackManager?, callback: FacebookCallback<LoginResult>?)
259
fun unregisterCallback(callbackManager: CallbackManager?)
260
261
// Activity result contract
262
fun createLogInActivityResultContract(callbackManager: CallbackManager? = null, loggerID: String? = null): FacebookLoginActivityResultContract
263
264
fun logOut()
265
}
266
267
class LoginButton : FacebookButtonBase {
268
var permissions: List<String>
269
var loginBehavior: LoginBehavior
270
var defaultAudience: DefaultAudience
271
272
fun setPermissions(vararg permissions: String?)
273
fun registerCallback(
274
callbackManager: CallbackManager,
275
callback: FacebookCallback<LoginResult>
276
)
277
}
278
279
data class LoginResult(
280
val accessToken: AccessToken,
281
val recentlyGrantedPermissions: Set<String>,
282
val recentlyDeniedPermissions: Set<String>
283
)
284
```
285
286
[Facebook Login](./login.md)
287
288
### Graph API
289
290
Direct access to Facebook's Graph API for reading and writing Facebook data. Provides request building, batch operations, and response handling.
291
292
```kotlin { .api }
293
class GraphRequest private constructor() {
294
companion object {
295
fun newMeRequest(
296
accessToken: AccessToken?,
297
callback: GraphJSONObjectCallback?
298
): GraphRequest
299
300
fun newPostRequest(
301
accessToken: AccessToken?,
302
graphPath: String?,
303
graphObject: JSONObject?,
304
callback: Callback?
305
): GraphRequest
306
}
307
308
fun executeAsync(): GraphRequestAsyncTask
309
fun executeAndWait(): GraphResponse
310
311
interface Callback {
312
fun onCompleted(response: GraphResponse)
313
}
314
}
315
316
class GraphResponse(
317
request: GraphRequest,
318
connection: HttpURLConnection?,
319
error: FacebookRequestError?
320
) {
321
val jsonObject: JSONObject?
322
val jsonArray: JSONArray?
323
val error: FacebookRequestError?
324
}
325
```
326
327
[Graph API](./graph-api.md)
328
329
### Content Sharing
330
331
Comprehensive content sharing capabilities including links, photos, videos, and Open Graph stories. Supports both programmatic sharing and UI-based sharing dialogs.
332
333
```kotlin { .api }
334
class ShareApi(
335
content: ShareContent<*, *>,
336
mode: ShareApi.Mode
337
) {
338
enum class Mode { AUTOMATIC, NATIVE, WEB }
339
340
fun share(callback: FacebookCallback<Sharer.Result>?)
341
fun canShare(): Boolean
342
}
343
344
class ShareDialog : FacebookDialogBase<ShareContent<*, *>, ShareDialog.Result> {
345
companion object {
346
fun canShow(contentType: Class<out ShareContent<*, *>>): Boolean
347
}
348
349
fun show(content: ShareContent<*, *>)
350
}
351
352
abstract class ShareContent<P : ShareContent<P, E>, E : ShareContent.Builder<P, E>> {
353
val contentUrl: Uri?
354
val peopleIds: List<String>
355
val placeId: String?
356
val ref: String?
357
val shareHashtag: ShareHashtag?
358
}
359
```
360
361
[Content Sharing](./sharing.md)
362
363
### App Events & Analytics
364
365
Advanced analytics and event tracking system for measuring app performance, user engagement, and conversion tracking.
366
367
```kotlin { .api }
368
class AppEventsLogger private constructor() {
369
companion object {
370
fun newLogger(context: Context): AppEventsLogger
371
fun activateApp(application: Application)
372
fun deactivateApp(application: Application)
373
}
374
375
fun logEvent(eventName: String)
376
fun logEvent(eventName: String, parameters: Bundle?)
377
fun logEvent(eventName: String, valueToSum: Double)
378
fun logEvent(eventName: String, valueToSum: Double, parameters: Bundle?)
379
fun logPurchase(purchaseAmount: BigDecimal, currency: Currency)
380
fun flush()
381
}
382
```
383
384
[App Events & Analytics](./app-events.md)
385
386
### App Links
387
388
Deep linking functionality for seamless navigation between apps and handling of Facebook App Links.
389
390
```kotlin { .api }
391
class AppLinkData private constructor() {
392
val targetUri: Uri?
393
val ref: String?
394
val extras: Bundle?
395
val argumentBundle: Bundle?
396
397
companion object {
398
fun fetchDeferredAppLinkData(
399
context: Context,
400
callback: CompletionHandler
401
)
402
403
fun createFromActivity(activity: Activity): AppLinkData?
404
fun createFromAlBundle(appLinkBundle: Bundle): AppLinkData?
405
}
406
407
interface CompletionHandler {
408
fun onDeferredAppLinkDataFetched(appLinkData: AppLinkData?)
409
}
410
}
411
```
412
413
[App Links](./app-links.md)
414
415
### Messenger Integration
416
417
Direct integration with Facebook Messenger for sharing content and creating rich messaging experiences.
418
419
```kotlin { .api }
420
object MessengerUtils {
421
fun openMessengerInPlayStore(context: Context)
422
fun hasMessengerInstalled(context: Context): Boolean
423
fun shareToMessenger(
424
activity: Activity,
425
requestCode: Int,
426
shareToMessengerParams: ShareToMessengerParams
427
)
428
}
429
430
class ShareToMessengerParams private constructor() {
431
val uri: Uri?
432
val mimeType: String?
433
val metaData: Bundle?
434
435
class Builder {
436
fun setUri(uri: Uri): Builder
437
fun setMimeType(mimeType: String): Builder
438
fun setMetaData(metaData: Bundle): Builder
439
fun build(): ShareToMessengerParams
440
}
441
}
442
```
443
444
[Messenger Integration](./messenger.md)
445
446
### Gaming Services
447
448
Gaming-specific features including tournaments, gaming contexts, friend finder, and social gaming capabilities.
449
450
```kotlin { .api }
451
class GamingContext private constructor() {
452
val identifier: String?
453
454
companion object {
455
fun getCurrentGamingContext(): GamingContext?
456
fun switchGamingContext(
457
context: Context,
458
gamingContextId: String,
459
callback: FacebookCallback<GamingContext>
460
)
461
}
462
}
463
464
class FriendFinderDialog : FacebookDialogBase<Void, FriendFinderDialog.Result> {
465
fun show()
466
467
class Result(requestId: String, to: List<String>)
468
}
469
470
class TournamentFetcher {
471
companion object {
472
fun fetchTournaments(callback: FacebookCallback<List<Tournament>>)
473
}
474
}
475
```
476
477
[Gaming Services](./gaming.md)
478
479
### Asynchronous Tasks (Bolts)
480
481
Task management framework for handling asynchronous operations with continuation support and error handling.
482
483
```kotlin { .api }
484
class Task<TResult> private constructor() {
485
val isCompleted: Boolean
486
val isCancelled: Boolean
487
val isFaulted: Boolean
488
val result: TResult?
489
val error: Exception?
490
491
fun <TContinuationResult> continueWith(
492
continuation: Continuation<TResult, TContinuationResult>
493
): Task<TContinuationResult>
494
495
fun <TContinuationResult> onSuccess(
496
continuation: Continuation<TResult, TContinuationResult>
497
): Task<TContinuationResult>
498
499
companion object {
500
fun <TResult> call(callable: Callable<TResult>): Task<TResult>
501
fun <TResult> callInBackground(callable: Callable<TResult>): Task<TResult>
502
}
503
}
504
505
class TaskCompletionSource<TResult> {
506
val task: Task<TResult>
507
508
fun setResult(result: TResult)
509
fun setError(error: Exception)
510
fun setCancelled()
511
}
512
```
513
514
[Asynchronous Tasks](./bolts-tasks.md)
515
516
## Types
517
518
### Core Types
519
520
```kotlin { .api }
521
enum class AccessTokenSource {
522
FACEBOOK_APPLICATION_WEB,
523
FACEBOOK_APPLICATION_NATIVE,
524
FACEBOOK_APPLICATION_SERVICE,
525
WEB_VIEW,
526
CHROME_CUSTOM_TAB,
527
INSTAGRAM_APPLICATION_WEB,
528
INSTAGRAM_CUSTOM_CHROME_TAB,
529
INSTAGRAM_WEB_VIEW
530
}
531
532
enum class LoginBehavior {
533
NATIVE_WITH_FALLBACK,
534
NATIVE_ONLY,
535
WEB_ONLY,
536
WEB_VIEW_ONLY,
537
KATANA_ONLY,
538
DIALOG_ONLY
539
}
540
541
enum class DefaultAudience {
542
ONLY_ME,
543
FRIENDS,
544
EVERYONE
545
}
546
547
enum class LoginTargetApp {
548
FACEBOOK,
549
550
}
551
552
enum class HttpMethod {
553
GET, POST, DELETE
554
}
555
556
class LoginConfiguration(
557
permissions: Collection<String>? = null,
558
nonce: String? = null,
559
codeVerifier: String? = null
560
) {
561
val permissions: Collection<String>
562
val nonce: String?
563
val codeVerifier: String
564
}
565
566
data class LoginResult(
567
val accessToken: AccessToken,
568
val authenticationToken: AuthenticationToken?,
569
val recentlyGrantedPermissions: Set<String>,
570
val recentlyDeniedPermissions: Set<String>
571
)
572
573
interface LoginStatusCallback {
574
fun onCompleted(accessToken: AccessToken)
575
fun onFailure()
576
fun onError(exception: Exception)
577
}
578
579
interface CallbackManager {
580
fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean
581
582
object Factory {
583
fun create(): CallbackManager
584
}
585
}
586
587
interface FacebookCallback<T> {
588
fun onSuccess(result: T)
589
fun onCancel()
590
fun onError(error: FacebookException)
591
}
592
```
593
594
### Exception Types
595
596
```kotlin { .api }
597
open class FacebookException(message: String?) : RuntimeException(message)
598
599
class FacebookAuthorizationException(message: String?) : FacebookException(message)
600
601
class FacebookOperationCanceledException(message: String?) : FacebookException(message)
602
603
class FacebookServiceException(
604
error: FacebookRequestError,
605
errorMessage: String?
606
) : FacebookException(errorMessage)
607
608
class FacebookSdkNotInitializedException(message: String?) : FacebookException(message)
609
```