or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

app-events.mdapp-links.mdbolts-tasks.mdcore-authentication.mdgaming.mdgraph-api.mdindex.mdlogin.mdmessenger.mdsharing.md

app-events.mddocs/

0

# App Events & Analytics

1

2

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.

3

4

## App Events Logger

5

6

The primary interface for logging events and analytics data:

7

8

```kotlin { .api }

9

class AppEventsLogger private constructor() {

10

companion object {

11

// Logger creation

12

fun newLogger(context: Context): AppEventsLogger

13

fun newLogger(context: Context, applicationId: String?): AppEventsLogger

14

15

// Application lifecycle

16

fun activateApp(application: Application)

17

fun activateApp(application: Application, applicationId: String?)

18

fun deactivateApp(application: Application)

19

fun deactivateApp(application: Application, applicationId: String?)

20

21

// Device ID management

22

fun getAnonymousAppDeviceGUID(context: Context): String

23

fun setUserID(userID: String?)

24

fun getUserID(): String?

25

fun clearUserID()

26

27

// Privacy and data usage

28

fun setDataProcessingOptions(options: Array<String>?)

29

fun setDataProcessingOptions(options: Array<String>?, country: Int, state: Int)

30

fun setPushNotificationsRegistrationId(registrationId: String?)

31

32

// Event parameter limits

33

fun getFlushBehavior(): FlushBehavior

34

fun setFlushBehavior(flushBehavior: FlushBehavior)

35

}

36

37

// Basic event logging

38

fun logEvent(eventName: String)

39

fun logEvent(eventName: String, valueToSum: Double)

40

fun logEvent(eventName: String, parameters: Bundle?)

41

fun logEvent(eventName: String, valueToSum: Double, parameters: Bundle?)

42

43

// Purchase events

44

fun logPurchase(purchaseAmount: BigDecimal, currency: Currency)

45

fun logPurchase(purchaseAmount: BigDecimal, currency: Currency, parameters: Bundle?)

46

47

// Product catalog events

48

fun logProductItem(

49

itemID: String,

50

availability: ProductAvailability,

51

condition: ProductCondition,

52

description: String?,

53

imageLink: String?,

54

link: String?,

55

title: String?,

56

priceAmount: BigDecimal,

57

currency: Currency,

58

gtin: String?,

59

mpn: String?,

60

brand: String?,

61

parameters: Bundle?

62

)

63

64

// Push notification events

65

fun logPushNotificationOpen(payload: Bundle?)

66

fun logPushNotificationOpen(payload: Bundle?, action: String?)

67

68

// Control methods

69

fun flush()

70

fun isValidForAccessToken(accessToken: AccessToken?): Boolean

71

72

enum class FlushBehavior {

73

AUTO, // Automatic flushing

74

EXPLICIT_ONLY // Manual flushing only

75

}

76

77

enum class ProductAvailability {

78

IN_STOCK,

79

OUT_OF_STOCK,

80

PREORDER,

81

AVAILABLE_FOR_ORDER,

82

DISCONTINUED

83

}

84

85

enum class ProductCondition {

86

NEW,

87

REFURBISHED,

88

USED

89

}

90

}

91

```

92

93

### Basic Event Logging

94

95

```kotlin

96

class MainActivity : AppCompatActivity() {

97

private lateinit var logger: AppEventsLogger

98

99

override fun onCreate(savedInstanceState: Bundle?) {

100

super.onCreate(savedInstanceState)

101

102

// Create logger instance

103

logger = AppEventsLogger.newLogger(this)

104

105

// Log simple events

106

logger.logEvent("app_launched")

107

logger.logEvent("button_clicked", Bundle().apply {

108

putString("button_name", "main_cta")

109

putString("screen_name", "main")

110

})

111

112

// Log events with numeric values

113

logger.logEvent("level_completed", 125.0, Bundle().apply {

114

putInt("level", 5)

115

putDouble("score", 125.0)

116

putLong("time_spent", 180) // seconds

117

})

118

}

119

120

override fun onResume() {

121

super.onResume()

122

// Automatically handled by AppEventsLogger.activateApp()

123

// but you can log custom session events

124

logger.logEvent("session_started")

125

}

126

127

override fun onPause() {

128

super.onPause()

129

logger.logEvent("session_ended")

130

logger.flush() // Force flush on pause

131

}

132

}

133

```

134

135

## Standard Events

136

137

Facebook provides predefined standard events for common app actions:

138

139

```kotlin { .api }

140

object AppEventsConstants {

141

// Standard event names

142

const val EVENT_NAME_ACHIEVED_LEVEL = "fb_mobile_level_achieved"

143

const val EVENT_NAME_ADDED_PAYMENT_INFO = "fb_mobile_add_payment_info"

144

const val EVENT_NAME_ADDED_TO_CART = "fb_mobile_add_to_cart"

145

const val EVENT_NAME_ADDED_TO_WISHLIST = "fb_mobile_add_to_wishlist"

146

const val EVENT_NAME_COMPLETED_REGISTRATION = "fb_mobile_complete_registration"

147

const val EVENT_NAME_COMPLETED_TUTORIAL = "fb_mobile_tutorial_completion"

148

const val EVENT_NAME_INITIATED_CHECKOUT = "fb_mobile_initiated_checkout"

149

const val EVENT_NAME_PURCHASED = "fb_mobile_purchase"

150

const val EVENT_NAME_RATED = "fb_mobile_rate"

151

const val EVENT_NAME_SEARCHED = "fb_mobile_search"

152

const val EVENT_NAME_SPENT_CREDITS = "fb_mobile_spent_credits"

153

const val EVENT_NAME_UNLOCKED_ACHIEVEMENT = "fb_mobile_achievement_unlocked"

154

const val EVENT_NAME_VIEWED_CONTENT = "fb_mobile_content_view"

155

const val EVENT_NAME_AD_IMPRESSION = "AdImpression"

156

const val EVENT_NAME_AD_CLICK = "AdClick"

157

158

// Standard parameter names

159

const val EVENT_PARAM_CONTENT_TYPE = "fb_content_type"

160

const val EVENT_PARAM_CONTENT_ID = "fb_content_id"

161

const val EVENT_PARAM_CURRENCY = "fb_currency"

162

const val EVENT_PARAM_DESCRIPTION = "fb_description"

163

const val EVENT_PARAM_LEVEL = "fb_level"

164

const val EVENT_PARAM_MAX_RATING_VALUE = "fb_max_rating_value"

165

const val EVENT_PARAM_NUM_ITEMS = "fb_num_items"

166

const val EVENT_PARAM_PAYMENT_INFO_AVAILABLE = "fb_payment_info_available"

167

const val EVENT_PARAM_REGISTRATION_METHOD = "fb_registration_method"

168

const val EVENT_PARAM_SEARCH_STRING = "fb_search_string"

169

const val EVENT_PARAM_SOURCE_APPLICATION = "fb_source_application"

170

const val EVENT_PARAM_SUCCESS = "fb_success"

171

}

172

```

173

174

### Standard Events Usage

175

176

```kotlin

177

// E-commerce events

178

fun logPurchase(items: List<Product>, totalAmount: BigDecimal) {

179

val parameters = Bundle().apply {

180

putInt(AppEventsConstants.EVENT_PARAM_NUM_ITEMS, items.size)

181

putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "product")

182

putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, items.joinToString(",") { it.id })

183

}

184

185

logger.logPurchase(totalAmount, Currency.getInstance("USD"), parameters)

186

}

187

188

fun logAddToCart(product: Product) {

189

val parameters = Bundle().apply {

190

putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "product")

191

putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, product.id)

192

putString(AppEventsConstants.EVENT_PARAM_CURRENCY, "USD")

193

}

194

195

logger.logEvent(AppEventsConstants.EVENT_NAME_ADDED_TO_CART, product.price, parameters)

196

}

197

198

// Gaming events

199

fun logLevelAchieved(level: Int, score: Double) {

200

val parameters = Bundle().apply {

201

putInt(AppEventsConstants.EVENT_PARAM_LEVEL, level)

202

putDouble("score", score)

203

}

204

205

logger.logEvent(AppEventsConstants.EVENT_NAME_ACHIEVED_LEVEL, parameters)

206

}

207

208

// Content events

209

fun logContentView(contentId: String, contentType: String) {

210

val parameters = Bundle().apply {

211

putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, contentId)

212

putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, contentType)

213

}

214

215

logger.logEvent(AppEventsConstants.EVENT_NAME_VIEWED_CONTENT, parameters)

216

}

217

```

218

219

## Application Lifecycle Events

220

221

Automatic tracking of app lifecycle events:

222

223

```kotlin

224

// In your Application class

225

class MyApplication : Application() {

226

override fun onCreate() {

227

super.onCreate()

228

229

// Initialize Facebook SDK

230

FacebookSdk.sdkInitialize(applicationContext)

231

232

// Enable automatic app event logging

233

FacebookSdk.setAutoLogAppEventsEnabled(true)

234

235

// This will automatically log app launches, installs, and sessions

236

AppEventsLogger.activateApp(this)

237

}

238

}

239

240

// Manual lifecycle logging (if automatic logging is disabled)

241

class MainActivity : AppCompatActivity() {

242

override fun onResume() {

243

super.onResume()

244

AppEventsLogger.activateApp(application)

245

}

246

247

override fun onPause() {

248

super.onPause()

249

AppEventsLogger.deactivateApp(application)

250

}

251

}

252

```

253

254

## User Properties and Segmentation

255

256

Set user properties for better analytics segmentation:

257

258

```kotlin

259

// Set user ID for cross-device tracking

260

AppEventsLogger.setUserID("user123456")

261

262

// Log user registration

263

fun logUserRegistration(method: String, success: Boolean) {

264

val parameters = Bundle().apply {

265

putString(AppEventsConstants.EVENT_PARAM_REGISTRATION_METHOD, method)

266

putInt(AppEventsConstants.EVENT_PARAM_SUCCESS, if (success) 1 else 0)

267

}

268

269

logger.logEvent(AppEventsConstants.EVENT_NAME_COMPLETED_REGISTRATION, parameters)

270

}

271

272

// Set user data for advanced matching (hashed automatically)

273

AppEventsLogger.setUserData(

274

email = "user@example.com",

275

firstName = "John",

276

lastName = "Doe",

277

phone = "+1234567890",

278

dateOfBirth = "1990-01-01",

279

gender = "m",

280

city = "New York",

281

state = "NY",

282

zip = "10001",

283

country = "US"

284

)

285

```

286

287

## Custom Conversions and Funnels

288

289

Track custom conversion events and user journeys:

290

291

```kotlin

292

// Track conversion funnel

293

class ConversionTracker {

294

private val logger = AppEventsLogger.newLogger(context)

295

296

fun trackFunnelStep(step: String, stepNumber: Int, additionalData: Map<String, Any> = emptyMap()) {

297

val parameters = Bundle().apply {

298

putString("funnel_step", step)

299

putInt("step_number", stepNumber)

300

additionalData.forEach { (key, value) ->

301

when (value) {

302

is String -> putString(key, value)

303

is Int -> putInt(key, value)

304

is Double -> putDouble(key, value)

305

is Boolean -> putBoolean(key, value)

306

}

307

}

308

}

309

310

logger.logEvent("conversion_funnel", parameters)

311

}

312

313

fun trackCustomConversion(conversionName: String, value: Double = 0.0) {

314

val parameters = Bundle().apply {

315

putString("conversion_type", conversionName)

316

putDouble("conversion_value", value)

317

putLong("timestamp", System.currentTimeMillis())

318

}

319

320

logger.logEvent("custom_conversion", value, parameters)

321

}

322

}

323

324

// Usage

325

val tracker = ConversionTracker()

326

tracker.trackFunnelStep("product_page_view", 1, mapOf("product_id" to "ABC123"))

327

tracker.trackFunnelStep("add_to_cart", 2, mapOf("product_id" to "ABC123"))

328

tracker.trackFunnelStep("checkout_initiated", 3)

329

tracker.trackCustomConversion("premium_signup", 29.99)

330

```

331

332

## Push Notification Analytics

333

334

Track push notification performance:

335

336

```kotlin

337

// Log push notification received (in your FirebaseMessagingService)

338

class MyFirebaseMessagingService : FirebaseMessagingService() {

339

override fun onMessageReceived(remoteMessage: RemoteMessage) {

340

super.onMessageReceived(remoteMessage)

341

342

val logger = AppEventsLogger.newLogger(this)

343

val payload = Bundle().apply {

344

remoteMessage.data.forEach { (key, value) ->

345

putString(key, value)

346

}

347

}

348

349

// Log that push was received

350

logger.logEvent("push_notification_received", payload)

351

}

352

}

353

354

// Log push notification opened (in your activity)

355

class NotificationHandler {

356

fun handleNotificationClick(intent: Intent) {

357

val logger = AppEventsLogger.newLogger(context)

358

val extras = intent.extras

359

360

if (extras != null) {

361

logger.logPushNotificationOpen(extras)

362

363

// Log with custom action if user took specific action

364

val action = extras.getString("notification_action")

365

if (action != null) {

366

logger.logPushNotificationOpen(extras, action)

367

}

368

}

369

}

370

}

371

```

372

373

## Privacy and Data Control

374

375

Manage data collection and privacy settings:

376

377

```kotlin

378

// Data processing options for CCPA compliance

379

AppEventsLogger.setDataProcessingOptions(arrayOf("LDU"), 1, 1000) // California, specific state

380

381

// Disable data processing entirely

382

AppEventsLogger.setDataProcessingOptions(arrayOf("LDU"))

383

384

// Set user data usage limitations

385

FacebookSdk.setLimitEventAndDataUsage(context, true)

386

387

// Control advertiser ID collection

388

FacebookSdk.setAdvertiserIDCollectionEnabled(false)

389

390

// Clear user data

391

AppEventsLogger.clearUserID()

392

AppEventsLogger.clearUserData()

393

```

394

395

## Advanced Configuration

396

397

```kotlin

398

// Configure flush behavior

399

AppEventsLogger.setFlushBehavior(AppEventsLogger.FlushBehavior.EXPLICIT_ONLY)

400

401

// Manual flush control

402

val logger = AppEventsLogger.newLogger(context)

403

logger.logEvent("important_event")

404

logger.flush() // Force immediate send

405

406

// Batch logging with periodic flush

407

class BatchEventLogger {

408

private val logger = AppEventsLogger.newLogger(context)

409

private val eventQueue = mutableListOf<Pair<String, Bundle?>>()

410

411

init {

412

// Flush every 30 seconds

413

Handler(Looper.getMainLooper()).post(object : Runnable {

414

override fun run() {

415

flushEvents()

416

Handler(Looper.getMainLooper()).postDelayed(this, 30000)

417

}

418

})

419

}

420

421

fun queueEvent(eventName: String, parameters: Bundle? = null) {

422

synchronized(eventQueue) {

423

eventQueue.add(eventName to parameters)

424

}

425

}

426

427

private fun flushEvents() {

428

synchronized(eventQueue) {

429

eventQueue.forEach { (eventName, parameters) ->

430

logger.logEvent(eventName, parameters)

431

}

432

eventQueue.clear()

433

logger.flush()

434

}

435

}

436

}

437

```

438

439

## Testing and Debugging

440

441

Debug and test your app events implementation:

442

443

```kotlin

444

// Enable debug logging in development

445

if (BuildConfig.DEBUG) {

446

FacebookSdk.setIsDebugEnabled(true)

447

FacebookSdk.addLoggingBehavior(LoggingBehavior.APP_EVENTS)

448

}

449

450

// Test events in Facebook Analytics dashboard

451

class EventTester {

452

fun testAllEvents() {

453

val logger = AppEventsLogger.newLogger(context)

454

455

// Test standard events

456

logger.logEvent(AppEventsConstants.EVENT_NAME_VIEWED_CONTENT, Bundle().apply {

457

putString(AppEventsConstants.EVENT_PARAM_CONTENT_ID, "test_content")

458

putString(AppEventsConstants.EVENT_PARAM_CONTENT_TYPE, "test")

459

})

460

461

// Test purchase event

462

logger.logPurchase(BigDecimal("9.99"), Currency.getInstance("USD"), Bundle().apply {

463

putString("test_purchase", "true")

464

})

465

466

// Test custom events

467

logger.logEvent("test_custom_event", Bundle().apply {

468

putString("test_param", "test_value")

469

putLong("timestamp", System.currentTimeMillis())

470

})

471

472

// Force flush for immediate testing

473

logger.flush()

474

}

475

}

476

```