Getting Started with the Facebook SDK for Android: A Beginner’s GuideFacebook’s SDK for Android provides tools to integrate Facebook login, sharing, analytics, and other platform features into your Android app. This guide walks you through the basics: setting up your environment, installing the SDK, authenticating users, sharing content, tracking events with analytics, and troubleshooting common issues. By the end you’ll have a functional sample app that uses Facebook Login and an example of sharing and analytics.
Table of contents
- Prerequisites
- Create a Facebook App and Configure Settings
- Set up an Android project
- Add the Facebook SDK to your project
- Initialize the SDK and configure the manifest
- Implement Facebook Login
- Implement sharing (Share Dialog)
- Track events with Facebook Analytics (App Events)
- Permissions and privacy considerations
- Testing and troubleshooting
- Example: simple sample app
- Next steps and best practices
- Useful links and references
1. Prerequisites
- Android Studio installed (Arctic Fox or later recommended).
- A physical Android device or emulator running Android 6.0 (API 23) or later. Facebook features may need Google Play services on device emulators.
- A registered Facebook developer account. Sign up at developers.facebook.com.
- Familiarity with Kotlin or Java (this guide uses Kotlin examples).
2. Create a Facebook App and Configure Settings
- Go to developers.facebook.com and sign in.
- Click “My Apps” → “Create App”. Choose the business or consumer type appropriate for your app.
- Enter an App Display Name and contact email; click Create.
- In the Dashboard, add the “Facebook Login” product.
- Configure the OAuth redirect URIs and the package name / class name for Android:
- In Settings → Basic: note your App ID and App Secret. Keep the App Secret private.
- Under Facebook Login → Settings, add your OAuth redirect URIs if using web flows.
- In Settings → Advanced, ensure the platform is set to Android if necessary.
- Add Android platform and enter:
- Package Name (applicationId from your app’s Gradle).
- Default Activity Class Name (e.g., com.example.myapp.MainActivity).
- Key Hashes — you must generate and add at least one key hash (development and production). On macOS/Linux you can generate with:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
The default debug keystore password is “android”. On Windows adjust path accordingly.
3. Set up an Android project
- Open Android Studio → New Project → Empty Activity.
- Choose Kotlin as the language.
- Set minimum SDK (API 23+ recommended).
- Wait for Gradle sync to finish.
4. Add the Facebook SDK to your project
The Facebook SDK is distributed via Maven. Add the dependencies to your app-level build.gradle (Kotlin DSL or Groovy). Example (Groovy):
dependencies { implementation 'com.facebook.android:facebook-android-sdk:17.0.0' }
Replace the version with the latest stable release. In Kotlin DSL:
dependencies { implementation("com.facebook.android:facebook-android-sdk:17.0.0") }
Also ensure you have Maven Central in your repositories:
repositories { mavenCentral() }
Sync the project.
5. Initialize the SDK and configure the manifest
- Add the Internet permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET"/>
- Add the Facebook App ID and meta-data entries and the FacebookActivity (SDK provides) to your manifest inside the application tag:
<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_client_token"/> <activity android:name="com.facebook.FacebookActivity" android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation" android:label="@string/app_name" />
- Add the provider and ContentProvider if using certain SDK features (check current SDK docs).
- Initialize the SDK in your Application class or MainActivity before using any Facebook APIs:
class MyApplication : Application() { override fun onCreate() { super.onCreate() FacebookSdk.sdkInitialize(applicationContext) AppEventsLogger.activateApp(this) } }
Declare this application class in the manifest:
<application android:name=".MyApplication" ...>
Note: As SDKs evolve, initialization steps can change; check official docs for the exact initialization call for your SDK version.
6. Implement Facebook Login
- Add a LoginButton to your layout or use the LoginManager for a custom button.
Layout example:
<com.facebook.login.widget.LoginButton android:id="@+id/login_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" />
Activity code (Kotlin):
class MainActivity : AppCompatActivity() { private lateinit var callbackManager: CallbackManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) callbackManager = CallbackManager.Factory.create() val loginButton = findViewById<LoginButton>(R.id.login_button) loginButton.setPermissions(listOf("email", "public_profile")) loginButton.registerCallback(callbackManager, object: FacebookCallback<LoginResult> { override fun onSuccess(result: LoginResult) { val accessToken = result.accessToken // Use accessToken to call Graph API or send to your backend } override fun onCancel() { /* Handle cancel */ } override fun onError(error: FacebookException) { /* Handle error */ } }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) callbackManager.onActivityResult(requestCode, resultCode, data) } }
-
For a custom button, call LoginManager.getInstance().logInWithReadPermissions(this, listOf(“email”)) and handle callbacks similarly.
-
Exchange the short-lived access token for a long-lived token on your server if you need longer session lifetime.
7. Implement sharing (Share Dialog)
Use the Share Dialog to let users share links or media without requiring publish permissions.
Example: share a link
val shareDialog = ShareDialog(this) if (ShareDialog.canShow(ShareLinkContent::class.java)) { val content = ShareLinkContent.Builder() .setContentUrl(Uri.parse("https://example.com")) .setQuote("Check this out!") .build() shareDialog.show(content) }
For photo sharing or sharing to Stories, follow the SDK documentation for required content builders and permissions.
8. Track events with Facebook Analytics (App Events)
App Events let you measure installs, purchases, and custom events.
-
Log an event:
AppEventsLogger.newLogger(context).logEvent("tutorial_completed")
-
Standard events like PURCHASE should use the provided constants and include currency and value parameters for accurate reporting.
-
Verify events in the Event Debugging tools on the Facebook developer dashboard.
9. Permissions and privacy considerations
- Request only the permissions you need. Public profile and email are common read permissions. Publishing to a user’s timeline requires review for publish permissions.
- Always disclose to users what data you collect and how it’s used in your privacy policy.
- Facebook may require App Review if you request extended permissions or access to certain APIs. Submit screencasts and detailed explanations when prompted.
- Safeguard the App Secret and never embed it in client-side code.
10. Testing and troubleshooting
- Add your development key hash to the Facebook app settings; missing key hashes are a common cause of login failures.
- Use the Facebook Login Troubleshooter in the developer console to diagnose issues.
- Check logcat for Facebook SDK logs (tagged com.facebook).
- If login returns permission errors, confirm requested permissions are approved or in development mode for tester accounts.
- Use test users from the Facebook developer dashboard for isolated testing.
11. Example: simple sample app
A minimal flow:
- User opens app → sees LoginButton.
- OnSuccess: retrieve user profile via GraphRequest:
val request = GraphRequest.newMeRequest(accessToken) { obj, response -> val name = obj?.getString("name") val email = obj?.getString("email") // Update UI } val parameters = Bundle() parameters.putString("fields", "id,name,email") request.parameters = parameters request.executeAsync()
- Provide a Share button to open ShareDialog with a URL.
- Log an event when user completes onboarding:
AppEventsLogger.newLogger(this).logEvent(AppEventsConstants.EVENT_NAME_COMPLETED_TUTORIAL)
12. Next steps and best practices
- Migrate to the latest SDK versions and follow changelogs.
- Use the Graph API and Webhooks as needed for server-side integrations.
- Implement secure backend token exchange and user account linking.
- Localize permission prompts and app strings.
- Monitor analytics and A/B test flows to improve conversion.
13. Useful links and references
- Facebook for Developers: SDK docs, Graph API, App Review, and troubleshooting pages.
- Android developer docs for secure storage and networking best practices.
If you want, I can: provide a complete sample Android project (Kotlin) you can import into Android Studio, generate the exact key hash command for your OS, or write the privacy-policy snippet needed for Facebook review.