CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-facebook-android--facebook-android-sdk

Facebook SDK for Android providing comprehensive integration with Facebook platform features including Login, Sharing, Messenger, App Links, Analytics, and Graph API

Pending
Overview
Eval results
Files

app-events.mddocs/

App Events & Analytics

The Facebook App Events system provides advanced analytics and event tracking capabilities for measuring app performance, user engagement, conversion tracking, and custom analytics. It enables automatic and manual event logging with comprehensive parameter support.

App Events Logger

The primary interface for logging events and analytics data:

class AppEventsLogger private constructor() {
    companion object {
        // Logger creation
        fun newLogger(context: Context): AppEventsLogger
        fun newLogger(context: Context, applicationId: String?): AppEventsLogger
        
        // Application lifecycle
        fun activateApp(application: Application)
        fun activateApp(application: Application, applicationId: String?)
        fun deactivateApp(application: Application)
        fun deactivateApp(application: Application, applicationId: String?)
        
        // Device ID management
        fun getAnonymousAppDeviceGUID(context: Context): String
        fun setUserID(userID: String?)
        fun getUserID(): String?
        fun clearUserID()
        
        // Privacy and data usage
        fun setDataProcessingOptions(options: Array<String>?)
        fun setDataProcessingOptions(options: Array<String>?, country: Int, state: Int)
        fun setPushNotificationsRegistrationId(registrationId: String?)
        
        // Event parameter limits
        fun getFlushBehavior(): FlushBehavior
        fun setFlushBehavior(flushBehavior: FlushBehavior)
    }
    
    // Basic event logging
    fun logEvent(eventName: String)
    fun logEvent(eventName: String, valueToSum: Double)
    fun logEvent(eventName: String, parameters: Bundle?)
    fun logEvent(eventName: String, valueToSum: Double, parameters: Bundle?)
    
    // Purchase events
    fun logPurchase(purchaseAmount: BigDecimal, currency: Currency)
    fun logPurchase(purchaseAmount: BigDecimal, currency: Currency, parameters: Bundle?)
    
    // Product catalog events
    fun logProductItem(
        itemID: String,
        availability: ProductAvailability,
        condition: ProductCondition,
        description: String?,
        imageLink: String?,
        link: String?,
        title: String?,
        priceAmount: BigDecimal,
        currency: Currency,
        gtin: String?,
        mpn: String?,
        brand: String?,
        parameters: Bundle?
    )
    
    // Push notification events
    fun logPushNotificationOpen(payload: Bundle?)
    fun logPushNotificationOpen(payload: Bundle?, action: String?)
    
    // Control methods
    fun flush()
    fun isValidForAccessToken(accessToken: AccessToken?): Boolean
    
    enum class FlushBehavior {
        AUTO,           // Automatic flushing
        EXPLICIT_ONLY   // Manual flushing only
    }
    
    enum class ProductAvailability {
        IN_STOCK,
        OUT_OF_STOCK,
        PREORDER,
        AVAILABLE_FOR_ORDER,
        DISCONTINUED
    }
    
    enum class ProductCondition {
        NEW,
        REFURBISHED,
        USED
    }
}

Basic Event Logging

class MainActivity : AppCompatActivity() {
    private lateinit var logger: AppEventsLogger
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // Create logger instance
        logger = AppEventsLogger.newLogger(this)
        
        // Log simple events
        logger.logEvent("app_launched")
        logger.logEvent("button_clicked", Bundle().apply {
            putString("button_name", "main_cta")
            putString("screen_name", "main")
        })
        
        // Log events with numeric values
        logger.logEvent("level_completed", 125.0, Bundle().apply {
            putInt("level", 5)
            putDouble("score", 125.0)
            putLong("time_spent", 180) // seconds
        })
    }
    
    override fun onResume() {
        super.onResume()
        // Automatically handled by AppEventsLogger.activateApp()
        // but you can log custom session events
        logger.logEvent("session_started")
    }
    
    override fun onPause() {
        super.onPause()
        logger.logEvent("session_ended")
        logger.flush() // Force flush on pause
    }
}

Standard Events

Facebook provides predefined standard events for common app actions:

object AppEventsConstants {
    // Standard event names
    const val EVENT_NAME_ACHIEVED_LEVEL = "fb_mobile_level_achieved"
    const val EVENT_NAME_ADDED_PAYMENT_INFO = "fb_mobile_add_payment_info"
    const val EVENT_NAME_ADDED_TO_CART = "fb_mobile_add_to_cart"
    const val EVENT_NAME_ADDED_TO_WISHLIST = "fb_mobile_add_to_wishlist"
    const val EVENT_NAME_COMPLETED_REGISTRATION = "fb_mobile_complete_registration"
    const val EVENT_NAME_COMPLETED_TUTORIAL = "fb_mobile_tutorial_completion"
    const val EVENT_NAME_INITIATED_CHECKOUT = "fb_mobile_initiated_checkout"
    const val EVENT_NAME_PURCHASED = "fb_mobile_purchase"
    const val EVENT_NAME_RATED = "fb_mobile_rate"
    const val EVENT_NAME_SEARCHED = "fb_mobile_search"
    const val EVENT_NAME_SPENT_CREDITS = "fb_mobile_spent_credits"
    const val EVENT_NAME_UNLOCKED_ACHIEVEMENT = "fb_mobile_achievement_unlocked"
    const val EVENT_NAME_VIEWED_CONTENT = "fb_mobile_content_view"
    const val EVENT_NAME_AD_IMPRESSION = "AdImpression"
    const val EVENT_NAME_AD_CLICK = "AdClick"
    
    // Standard parameter names
    const val EVENT_PARAM_CONTENT_TYPE = "fb_content_type"
    const val EVENT_PARAM_CONTENT_ID = "fb_content_id"
    const val EVENT_PARAM_CURRENCY = "fb_currency"
    const val EVENT_PARAM_DESCRIPTION = "fb_description"
    const val EVENT_PARAM_LEVEL = "fb_level"
    const val EVENT_PARAM_MAX_RATING_VALUE = "fb_max_rating_value"
    const val EVENT_PARAM_NUM_ITEMS = "fb_num_items"
    const val EVENT_PARAM_PAYMENT_INFO_AVAILABLE = "fb_payment_info_available"
    const val EVENT_PARAM_REGISTRATION_METHOD = "fb_registration_method"
    const val EVENT_PARAM_SEARCH_STRING = "fb_search_string"
    const val EVENT_PARAM_SOURCE_APPLICATION = "fb_source_application"
    const val EVENT_PARAM_SUCCESS = "fb_success"
}

Standard Events Usage

// E-commerce events
fun logPurchase(items: List<Product>, totalAmount: BigDecimal) {
    val parameters = Bundle().apply {
        putInt(AppEventsConstants.EVENT_PARAM_NUM_ITEMS, items.size)
        putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "product")
        putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, items.joinToString(",") { it.id })
    }
    
    logger.logPurchase(totalAmount, Currency.getInstance("USD"), parameters)
}

fun logAddToCart(product: Product) {
    val parameters = Bundle().apply {
        putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "product")
        putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, product.id)
        putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD")
    }
    
    logger.logEvent(AppEventsConstants.EVENT_NAME_ADDED_TO_CART, product.price, parameters)
}

// Gaming events
fun logLevelAchieved(level: Int, score: Double) {
    val parameters = Bundle().apply {
        putInt(AppEventsConstants.EVENT_PARAM_LEVEL, level)
        putDouble("score", score)
    }
    
    logger.logEvent(AppEventsConstants.EVENT_NAME_ACHIEVED_LEVEL, parameters)
}

// Content events
fun logContentView(contentId: String, contentType: String) {
    val parameters = Bundle().apply {
        putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, contentId)
        putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, contentType)
    }
    
    logger.logEvent(AppEventsConstants.EVENT_NAME_VIEWED_CONTENT, parameters)
}

Application Lifecycle Events

Automatic tracking of app lifecycle events:

// In your Application class
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // Initialize Facebook SDK
        FacebookSdk.sdkInitialize(applicationContext)
        
        // Enable automatic app event logging
        FacebookSdk.setAutoLogAppEventsEnabled(true)
        
        // This will automatically log app launches, installs, and sessions
        AppEventsLogger.activateApp(this)
    }
}

// Manual lifecycle logging (if automatic logging is disabled)
class MainActivity : AppCompatActivity() {
    override fun onResume() {
        super.onResume()
        AppEventsLogger.activateApp(application)
    }
    
    override fun onPause() {
        super.onPause()
        AppEventsLogger.deactivateApp(application)
    }
}

User Properties and Segmentation

Set user properties for better analytics segmentation:

// Set user ID for cross-device tracking
AppEventsLogger.setUserID("user123456")

// Log user registration
fun logUserRegistration(method: String, success: Boolean) {
    val parameters = Bundle().apply {
        putString(AppEventsConstants.EVENT_PARAM_REGISTRATION_METHOD, method)
        putInt(AppEventsConstants.EVENT_PARAM_SUCCESS, if (success) 1 else 0)
    }
    
    logger.logEvent(AppEventsConstants.EVENT_NAME_COMPLETED_REGISTRATION, parameters)
}

// Set user data for advanced matching (hashed automatically)
AppEventsLogger.setUserData(
    email = "user@example.com",
    firstName = "John",
    lastName = "Doe",
    phone = "+1234567890",
    dateOfBirth = "1990-01-01",
    gender = "m",
    city = "New York",
    state = "NY",
    zip = "10001",
    country = "US"
)

Custom Conversions and Funnels

Track custom conversion events and user journeys:

// Track conversion funnel
class ConversionTracker {
    private val logger = AppEventsLogger.newLogger(context)
    
    fun trackFunnelStep(step: String, stepNumber: Int, additionalData: Map<String, Any> = emptyMap()) {
        val parameters = Bundle().apply {
            putString("funnel_step", step)
            putInt("step_number", stepNumber)
            additionalData.forEach { (key, value) ->
                when (value) {
                    is String -> putString(key, value)
                    is Int -> putInt(key, value)
                    is Double -> putDouble(key, value)
                    is Boolean -> putBoolean(key, value)
                }
            }
        }
        
        logger.logEvent("conversion_funnel", parameters)
    }
    
    fun trackCustomConversion(conversionName: String, value: Double = 0.0) {
        val parameters = Bundle().apply {
            putString("conversion_type", conversionName)
            putDouble("conversion_value", value)
            putLong("timestamp", System.currentTimeMillis())
        }
        
        logger.logEvent("custom_conversion", value, parameters)
    }
}

// Usage
val tracker = ConversionTracker()
tracker.trackFunnelStep("product_page_view", 1, mapOf("product_id" to "ABC123"))
tracker.trackFunnelStep("add_to_cart", 2, mapOf("product_id" to "ABC123"))
tracker.trackFunnelStep("checkout_initiated", 3)
tracker.trackCustomConversion("premium_signup", 29.99)

Push Notification Analytics

Track push notification performance:

// Log push notification received (in your FirebaseMessagingService)
class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        
        val logger = AppEventsLogger.newLogger(this)
        val payload = Bundle().apply {
            remoteMessage.data.forEach { (key, value) ->
                putString(key, value)
            }
        }
        
        // Log that push was received
        logger.logEvent("push_notification_received", payload)
    }
}

// Log push notification opened (in your activity)
class NotificationHandler {
    fun handleNotificationClick(intent: Intent) {
        val logger = AppEventsLogger.newLogger(context)
        val extras = intent.extras
        
        if (extras != null) {
            logger.logPushNotificationOpen(extras)
            
            // Log with custom action if user took specific action
            val action = extras.getString("notification_action")
            if (action != null) {
                logger.logPushNotificationOpen(extras, action)
            }
        }
    }
}

Privacy and Data Control

Manage data collection and privacy settings:

// Data processing options for CCPA compliance
AppEventsLogger.setDataProcessingOptions(arrayOf("LDU"), 1, 1000) // California, specific state

// Disable data processing entirely
AppEventsLogger.setDataProcessingOptions(arrayOf("LDU"))

// Set user data usage limitations
FacebookSdk.setLimitEventAndDataUsage(context, true)

// Control advertiser ID collection
FacebookSdk.setAdvertiserIDCollectionEnabled(false)

// Clear user data
AppEventsLogger.clearUserID()
AppEventsLogger.clearUserData()

Advanced Configuration

// Configure flush behavior
AppEventsLogger.setFlushBehavior(AppEventsLogger.FlushBehavior.EXPLICIT_ONLY)

// Manual flush control
val logger = AppEventsLogger.newLogger(context)
logger.logEvent("important_event")
logger.flush() // Force immediate send

// Batch logging with periodic flush
class BatchEventLogger {
    private val logger = AppEventsLogger.newLogger(context)
    private val eventQueue = mutableListOf<Pair<String, Bundle?>>()
    
    init {
        // Flush every 30 seconds
        Handler(Looper.getMainLooper()).post(object : Runnable {
            override fun run() {
                flushEvents()
                Handler(Looper.getMainLooper()).postDelayed(this, 30000)
            }
        })
    }
    
    fun queueEvent(eventName: String, parameters: Bundle? = null) {
        synchronized(eventQueue) {
            eventQueue.add(eventName to parameters)
        }
    }
    
    private fun flushEvents() {
        synchronized(eventQueue) {
            eventQueue.forEach { (eventName, parameters) ->
                logger.logEvent(eventName, parameters)
            }
            eventQueue.clear()
            logger.flush()
        }
    }
}

Testing and Debugging

Debug and test your app events implementation:

// Enable debug logging in development
if (BuildConfig.DEBUG) {
    FacebookSdk.setIsDebugEnabled(true)
    FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS)
}

// Test events in Facebook Analytics dashboard
class EventTester {
    fun testAllEvents() {
        val logger = AppEventsLogger.newLogger(context)
        
        // Test standard events
        logger.logEvent(AppEventsConstants.EVENT_NAME_VIEWED_CONTENT, Bundle().apply {
            putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, "test_content")
            putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "test")
        })
        
        // Test purchase event
        logger.logPurchase(BigDecimal("9.99"), Currency.getInstance("USD"), Bundle().apply {
            putString("test_purchase", "true")
        })
        
        // Test custom events
        logger.logEvent("test_custom_event", Bundle().apply {
            putString("test_param", "test_value")
            putLong("timestamp", System.currentTimeMillis())
        })
        
        // Force flush for immediate testing
        logger.flush()
    }
}

Install with Tessl CLI

npx tessl i tessl/maven-com-facebook-android--facebook-android-sdk

docs

app-events.md

app-links.md

bolts-tasks.md

core-authentication.md

gaming.md

graph-api.md

index.md

login.md

messenger.md

sharing.md

tile.json