# Android SDK Integration Guide

Source: https://appfig.com/docs/android-integration

Complete guide to integrating AppFig into your Android application.

## Installation

> **SDK Download Repository:** [https://github.com/smartconfigui/AppFig-SDKs](https://github.com/smartconfigui/AppFig-SDKs)

**Requirements:** Android API 21+ (Android 5.0 Lollipop), Android Studio 4.0+, Gradle 7.0+

### Step 1 — Add the dependency

In your app module's build file.

**Groovy (build.gradle):**

```gradle
dependencies {
    implementation 'com.appfig:appfig-android:2.5.0'
}
```

**Kotlin DSL (build.gradle.kts):**

```kotlin
dependencies {
    implementation("com.appfig:appfig-android:2.5.0")
}
```

The SDK is on Maven Central, which a standard Android project already has in its repositories
(`mavenCentral()`). The libraries it needs (OkHttp, Gson, the Kotlin standard library) are pulled in
automatically, and it declares the internet permission itself.

### Step 2 — Sync Gradle

Android Studio → "Sync Project with Gradle Files".

### Without Maven Central

Projects that cannot use Maven Central can copy `android/AppFigAndroidSDK.aar` from the
[SDK repository](https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/android) into `app/libs/` and add
`implementation files('libs/AppFigAndroidSDK.aar')` together with
`com.squareup.okhttp3:okhttp:4.12.0` and `com.google.code.gson:gson:2.10.1`.

## Quick Start

### Initialize

```kotlin
import com.appfig.sdk.AppFig

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        // Initialize AppFig with auto-refresh
        AppFig.init(
            context = this,
            companyId = "your-company-id",
            tenantId = "your-tenant-id",
            env = "prod",
            apiKey = "your-api-key",
            autoRefresh = true,
            pollInterval = 3600000  // 1 hour
        )

        // Log events
        AppFig.logEvent("app_open")

        // Check features
        if (AppFig.isFeatureEnabled("double_xp")) {
            applyDoubleXP()
        }

        val maxLives = AppFig.getFeatureValue("max_lives")?.toIntOrNull() ?: 3
    }
}
```

## When to Do What: Timing Guide

Understanding WHEN to call each SDK method is crucial for proper Android integration:

| Action | When to Call | Where to Place | Code Example |
|--------|-------------|----------------|--------------|
| **Initialize SDK** | Once at app startup | `Application.onCreate()` | `AppFig.init(...)` |
| **Log Events** | Immediately after user action | onClick listeners, lifecycle methods | `AppFig.logEvent("button_click")` |
| **Set User Properties** | Once at login, when value changes | Auth callback, state change | `AppFig.setUserProperty("tier", "premium")` |
| **Evaluate Features** | Right before you need the value | onCreate, onResume, before decisions | `AppFig.getFeatureValue("max_lives")` |
| **Apply Features** | Immediately after evaluation | Same method as evaluation | `if (enabled) showUI()` |
| **Refresh Rules** | On demand (auto-refresh handles this) | Manual: Settings screen | `AppFig.refreshRules()` |

### Complete Lifecycle Example

```kotlin
import android.app.Application
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.appfig.sdk.AppFig

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()

        // 1. INITIALIZE: Once at app startup
        AppFig.init(
            context = this,
            companyId = "your-company-id",
            tenantId = "your-tenant-id",
            env = "prod",
            apiKey = "your-api-key"
        )

        // 2. TRACK: Log app open
        AppFig.logEvent("app_open")
    }
}

class MainActivity : AppCompatActivity() {
    private var playerLives = 3

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 3. EVALUATE: Check features when activity created
        checkWelcomeBonus()
        configureGameSettings()
    }

    private fun checkWelcomeBonus() {
        // Evaluate right before using
        if (AppFig.isFeatureEnabled("welcome_bonus")) {
            // 4. APPLY: Show bonus immediately
            findViewById<View>(R.id.welcomePanel).visibility = View.VISIBLE
            grantBonus(500)
        } else {
            findViewById<View>(R.id.welcomePanel).visibility = View.GONE
        }
    }

    private fun configureGameSettings() {
        // Evaluate with fallback
        val maxLives = AppFig.getFeatureValue("max_lives")?.toIntOrNull() ?: 3
        playerLives = maxLives

        // Apply to UI
        findViewById<TextView>(R.id.livesText).text = "Lives: $playerLives"
    }

    fun onLevelComplete(view: View) {
        // TRACK: Log immediately after action
        AppFig.logEvent("level_complete", mapOf(
            "level" to currentLevel.toString()
        ))

        // Re-evaluate features that depend on level
        checkNewUnlocks()
    }

    fun onSubscriptionPurchased(tier: String) {
        // Update property when it changes
        AppFig.setUserProperty("subscription_tier", tier)

        // Re-evaluate premium features
        updatePremiumFeatures()
    }
}
```

### Timing Best Practices

#### Initialize Once in Application Class

```kotlin
// ✅ CORRECT: Initialize in Application.onCreate()
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        AppFig.init(context = this, companyId = "...", tenantId = "...", env = "prod", apiKey = "...")
    }
}

// ❌ WRONG: Don't initialize in every activity
class MyActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        AppFig.init(...)  // Bad! SDK already initialized
    }
}
```

#### Log Events Immediately

```kotlin
// ✅ CORRECT: Log right when action happens
fun onPurchaseClicked(view: View) {
    AppFig.logEvent("purchase_initiated")
    showPurchaseDialog()
}

// ❌ WRONG: Don't batch events
private val pendingEvents = mutableListOf<String>()

fun onLevelComplete() {
    pendingEvents.add("level_complete")  // Bad!
}
```

#### Cache Feature Values

```kotlin
// ✅ CORRECT: Check once and cache
class GameActivity : AppCompatActivity() {
    private var hasDoubleXP = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        hasDoubleXP = AppFig.isFeatureEnabled("double_xp")
    }

    fun calculateXP(baseXP: Int): Int {
        return if (hasDoubleXP) baseXP * 2 else baseXP
    }
}

// ❌ WRONG: Don't check repeatedly
fun update() {
    if (AppFig.isFeatureEnabled("double_xp")) {  // Bad!
        applyDoubleXP()
    }
}
```

---

## API Reference

### Initialization

```kotlin
AppFig.init(
    context: Context,                     // Required: Application context
    companyId: String,                    // Required: Your company ID
    tenantId: String,                     // Required: Your tenant/project ID
    env: String,                          // Required: "dev" or "prod"
    apiKey: String,                       // Required: Your API key
    autoRefresh: Boolean = true,          // Optional: Enable auto-refresh (default: true) ✨ NEW DEFAULT
    pollInterval: Long = 43200000L,       // Optional: leave out to follow your plan
    debugMode: Boolean = false,           // Optional: Enable debug logging (default: false) ✨ NEW
    sessionTimeoutMs: Long = 1800000L,    // Optional: 30 minutes (default: 30 min) ✨ NEW
    maxEvents: Int = 5000,                // Optional: Max events (default: 5000, max: 100000)
    maxEventAgeDays: Int = 7,             // Optional: Max age in days (default: 7, max: 365)
    cdnBaseUrl: String? = null            // Optional: rules host (default: production) 🆕 2.3
)
```

**Parameters:**
- `context` (required) - Application context (use `this` from Application.onCreate() or activity)
- `companyId` (required) - Your company ID from AppFig dashboard
- `tenantId` (required) - Your tenant/project ID from AppFig dashboard
- `env` (required) - Environment: `"dev"` or `"prod"`
- `apiKey` (required) - Your API key from AppFig dashboard
- `autoRefresh` (optional) - Enable automatic background rule updates (default: **true**) ⚠️ **Breaking Change** Refreshing pauses while no screen of your app is visible and resumes when the app comes back to the foreground 🆕 **New in 2.4**.
- `pollInterval` (optional) - Auto-refresh interval in milliseconds. Leave it out and the SDK checks for changes every minute, on every plan 🆕 **New in 2.3**. A value you set is kept, but never faster than your plan allows.
- `debugMode` (optional) - Enable debug logging to Logcat (default: false) 🆕 **New in v2.0**
- `sessionTimeoutMs` (optional) - Session timeout in milliseconds (default: 1800000L = 30 min, range: 60000-7200000) 🆕 **New in v2.0**
- `maxEvents` (optional) - Maximum events to store in SharedPreferences (100-100000, default: 5000)
- `maxEventAgeDays` (optional) - Maximum age of events in days (1-365, default: 7)
- `cdnBaseUrl` (optional) - The rules host to read from, e.g. `https://rules-stage.appfig.com` for a staging build. Leave it out for production (`https://rules-prod.appfig.com`). Must start with `https://`. 🆕 **New in 2.3**

**Examples:**

```kotlin
// Basic initialization (auto-refresh enabled by default)
AppFig.init(this, "acme-games", "space-shooter", "prod", "sk_live_abc123")

// With a fixed poll interval (1 hour)
AppFig.init(
    context = this,
    companyId = "acme-games",
    tenantId = "space-shooter",
    env = "prod",
    apiKey = "sk_live_abc123",
    autoRefresh = true,          // Explicit (but this is already the default)
    pollInterval = 3600000L      // 1 hour
)

// With debug mode enabled (useful during development)
AppFig.init(
    context = this,
    companyId = "acme-games",
    tenantId = "space-shooter",
    env = "dev",                 // Use dev environment
    apiKey = "sk_test_abc123",
    autoRefresh = true,
    pollInterval = 600000L,      // 10 minutes for faster testing
    debugMode = true             // See all SDK operations in Logcat
)

// With all parameters customized
AppFig.init(
    context = this,
    companyId = "acme-games",
    tenantId = "space-shooter",
    env = "prod",
    apiKey = "sk_live_abc123",
    autoRefresh = true,
    pollInterval = 3600000L,
    debugMode = false,
    sessionTimeoutMs = 900000L,  // 15 minutes instead of 30
    maxEvents = 10000,           // Store more events
    maxEventAgeDays = 30         // Keep events for 30 days
)

// Disable auto-refresh (opt-out, manual refresh only)
AppFig.init(
    context = this,
    companyId = "acme-games",
    tenantId = "space-shooter",
    env = "prod",
    apiKey = "sk_live_abc123",
    autoRefresh = false          // Must call refreshRules() manually
)
```

### Logging Events

```kotlin
AppFig.logEvent(eventName: String, parameters: Map<String, String>? = null)
```

**Examples:**
```kotlin
// Simple event
AppFig.logEvent("level_complete")

// Event with parameters
AppFig.logEvent("purchase_made", mapOf(
    "item_id" to "sword_legendary",
    "price" to "9.99",
    "currency" to "USD"
))

// Screen view (auto-tracked by SDK too)
AppFig.logScreenView("main_menu", "settings")
```

### Checking Features

```kotlin
AppFig.isFeatureEnabled(feature: String): Boolean
AppFig.getFeatureValue(feature: String): String?
```

**Examples:**
```kotlin
// Boolean check (returns true if value == "on")
if (AppFig.isFeatureEnabled("new_ui")) {
    loadNewUI()
} else {
    loadOldUI()
}

// Get actual value
val maxLives = AppFig.getFeatureValue("max_lives")
if (maxLives != null) {
    playerLives = maxLives.toIntOrNull() ?: 3
}

// Handle null (no matching rules)
val bonus = AppFig.getFeatureValue("veteran_bonus")
if (bonus == null) {
    Log.d("AppFig", "No bonus active")
} else {
    applyBonus(bonus) // "2x", "1.5x", etc.
}
```

### Setting Properties

```kotlin
// User properties
AppFig.setUserProperty(key: String, value: String)
AppFig.removeUserProperty(key: String)

// Device properties
AppFig.setDeviceProperty(key: String, value: String)
AppFig.removeDeviceProperty(key: String)

// App version
AppFig.setAppVersion(version: String)
```

**Examples:**
```kotlin
// User properties
AppFig.setUserProperty("subscription_tier", "premium")
AppFig.setUserProperty("account_age_days", "30")
AppFig.setUserProperty("player_level", "15")

// Device properties (most are auto-detected)
AppFig.setAppVersion("1.2.3")
AppFig.setDeviceProperty("graphics_quality", "high")

// Remove properties
AppFig.removeUserProperty("subscription_tier")
```

### Auto-Detected Device Properties

These are automatically set by the SDK on initialization:

```
platform          "Android"
os_version        "13", "12", "11"
language          "English", "Japanese", "Spanish"
timezone          "America/Los_Angeles", "Asia/Tokyo"
country           "US", "JP", "GB" (requires internet on first run)
device_brand      "Samsung", "Google", "Huawei", "OnePlus"
device_model      "SM-G998B", "Pixel 8", "OnePlus 11"
```

### Session Tracking

Automatically tracked:

```kotlin
// These events are logged automatically:
"first_open"     // First time app opens (persisted in SharedPreferences)
"session_start"  // App comes to foreground
"session_end"    // App goes to background or 10 minutes of inactivity
"screen_view"    // When you call logScreenView()
```

### Manual Refresh

```kotlin
AppFig.refreshRules()  // Manually reload rules from CDN
```

**Example:**
```kotlin
// Manually refresh rules (useful for pull-to-refresh)
AppFig.refreshRules()
```

**Note:** `setAutoRefresh()` and `setPollInterval()` are deprecated. Use the `autoRefresh` and `pollInterval` parameters in `init()` instead.

### Feature Reset (Recurring Triggers)

```kotlin
AppFig.resetFeature(featureName: String)
AppFig.resetAllFeatures()
```

Reset a feature's cached value and force re-evaluation. Useful for implementing recurring triggers like "show popup every 3 events".

**Example:**
```kotlin
// Check if feature is enabled
if (AppFig.isFeatureEnabled("level_complete_popup")) {
    showPopup("You've completed 3 levels!")

    // Reset so it triggers again after next 3 events
    AppFig.resetFeature("level_complete_popup")
}

// With event logging
fun onLevelComplete(level: Int) {
    AppFig.logEvent("level_complete", mapOf("level" to level.toString()))

    // Check for milestone reward
    if (AppFig.isFeatureEnabled("milestone_reward")) {
        showReward()
        AppFig.resetFeature("milestone_reward")
    }
}
```

**Use Cases:**
- Show popup every N events (e.g., every 3 level completions)
- Recurring promotions after X purchases
- Periodic reward unlocks
- Time-based feature re-triggers

See [Feature Reset Guide](../../SDKs/FEATURE_RESET_GUIDE.md) for detailed examples.

### Debugging

```kotlin
AppFig.hasRulesLoaded(): Boolean
AppFig.getEventHistoryStats(): Map<String, Any>
```

**Example:**
```kotlin
if (AppFig.hasRulesLoaded()) {
    Log.d("AppFig", "Rules are loaded")
}

val stats = AppFig.getEventHistoryStats()
Log.d("AppFig", "Event count: ${stats["count"]}")
Log.d("AppFig", "Size: ${stats["sizeMB"]} MB")
```

## Best Practices

### 1. Initialize in Application Class

```kotlin
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        AppFig.init(
            context = this,
            companyId = "company",
            tenantId = "tenant",
            env = "prod",
            apiKey = "api-key",
            autoRefresh = true
        )
    }
}
```

Don't forget to register in `AndroidManifest.xml`:
```xml
<application
    android:name=".MyApplication"
    ...>
```

### 2. Cache Feature Values

```kotlin
// ❌ Bad: Checks every frame
override fun onDraw(canvas: Canvas) {
    if (AppFig.isFeatureEnabled("double_xp")) {
        // ...
    }
}

// ✅ Good: Check once, store result
private val hasDoubleXP by lazy { AppFig.isFeatureEnabled("double_xp") }

override fun onDraw(canvas: Canvas) {
    if (hasDoubleXP) {
        // ...
    }
}
```

### 3. Handle Null Values

```kotlin
val maxLives = AppFig.getFeatureValue("max_lives")?.toIntOrNull() ?: 5 // fallback
```

### 4. Log Events Liberally

```kotlin
fun completeLevel(level: Int, stars: Int, timeSeconds: Int) {
    AppFig.logEvent("level_complete", mapOf(
        "level_number" to level.toString(),
        "time_seconds" to timeSeconds.toString(),
        "stars" to stars.toString()
    ))
}
```

## Troubleshooting

### AAR not recognized by Android Studio

**Problem:** Android Studio doesn't find AppFig classes

**Solutions:**
1. Verify `AppFigAndroidSDK.aar` is in `app/libs/` folder
2. Check `build.gradle` has `implementation files('libs/AppFigAndroidSDK.aar')`
3. Sync Gradle files (File → Sync Project with Gradle Files)
4. Clean and rebuild project (Build → Clean Project, then Build → Rebuild Project)

### "AppFig not initialized"

**Problem:** Calling SDK methods before `init()`

**Solution:**
```kotlin
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        AppFig.init(...)  // Must be first!
        AppFig.logEvent("app_open")  // Now OK
    }
}
```

### Feature always returns null

**Problem:** No rules match for this feature

**Solutions:**
1. Check feature name spelling (case-sensitive)
2. Verify rules are loaded: `AppFig.hasRulesLoaded()`
3. Log relevant events/properties before checking feature
4. Check Logcat for AppFig debug messages

### Rules not updating

**Problem:** Changes in dashboard not reflected in app

**Solutions:**
1. Wait for the refresh interval (one minute)
2. Call `AppFig.refreshRules()` manually
3. Check Logcat for "AppFig" tag messages
4. Verify internet connection

## Performance Tips

### Event History Management

The SDK automatically manages event history to maintain optimal performance. Events are automatically trimmed based on:
- Maximum event count (default: 5000)
- Maximum event age (default: 7 days)

### Memory and CPU Usage

AppFig has minimal memory and CPU overhead:
- Low memory footprint suitable for mobile devices
- Fast feature checks with intelligent caching
- Efficient rule evaluation

## Next Steps

- **[Rule Schema](https://appfig.com/docs/rule-schema)** - All rule options
- **[Testing Guide](https://appfig.com/docs/testing)** - Test your features
