# FireworkSdk API Reference

The `FireworkSdk` object is the main entry point for the Firework Android SDK. It provides methods for SDK initialization, player management, shopping, livestream, and advanced configurations.

## SDK Initialization

### init()

Initialize the Firework SDK with configuration.

**Signature:**

```kotlin
fun init(
    fireworkSdkConfig: FireworkSdkConfig,
    onSuccess: (() -> Unit)? = null,
    onError: ((FireworkInitError) -> Unit)? = null
)
```

**Parameters:**

* `fireworkSdkConfig` - SDK configuration built with `FireworkSdkConfig.Builder`
* `onSuccess` - Optional callback invoked on successful initialization
* `onError` - Optional callback invoked on initialization failure

**Example:**

```kotlin
val config = FireworkSdkConfig.Builder(context = this)
    .clientId("YOUR_CLIENT_ID")
    .imageLoader(GlideImageLoaderFactory.createInstance(context = this))
    .build()

FireworkSdk.init(
    fireworkSdkConfig = config,
    onSuccess = {
        // SDK initialized successfully
    },
    onError = { error ->
        when (error) {
            is FireworkInitError.InitializationError -> {
                // Handle initialization error
            }
            is FireworkInitError.AlreadyInitializedError -> {
                // SDK already initialized
            }
        }
    }
)
```

**See Also:** [Getting Started Guide](/firework-for-developers/android-sdk/integration-guide/getting-started.md)

### isSdkInitialized()

Checks whether the Firework SDK has been successfully initialized.

This method returns `true` if the SDK's initialization process has completed successfully, including dependency injection setup and all core modules registration. It is essential to verify initialization status before calling any other SDK methods to avoid runtime errors.

**Signature:**

```kotlin
fun isSdkInitialized()
```

#### Initialization Requirements

The SDK is considered initialized when both of the following conditions are met:

* The dependency injection (DI) system has been set up
* The `init` method has completed successfully with all modules registered

#### Use Cases

* **Conditional Feature Access**: Check initialization before accessing SDK features
* **Error Prevention**: Avoid crashes by verifying SDK readiness before operations
* **State Management**: Track SDK lifecycle in your application
* **Debugging**: Verify initialization status when troubleshooting integration issues

#### Important Notes

* This method is thread-safe and can be called from any thread
* Calling SDK methods before initialization will typically result in failures or exceptions
* The SDK can only be initialized once per application lifecycle
* If initialization fails, this method will return `false`

***

## Video Player

### startPlayer()

Launch the fullscreen video player.

#### Variant 1: With URL

Launch a specific video directly using its URL.

**Signature:**

```kotlin
fun startPlayer(
    viewOptions: ViewOptions,
    url: String
): PlayerLaunchResult
```

**Parameters:**

* `viewOptions` - Player configuration options
* `url` - Video URL to play

**Returns:** `PlayerLaunchResult` indicating success or failure

**Example:**

```kotlin
val viewOptions = viewOptions {
    playerOptions {
        showShareButton(true)
        enablePipMode(true)
    }
}

when (val result = FireworkSdk.startPlayer(viewOptions, "https://video-url")) {
    is PlayerLaunchResult.Success -> {
        // Player launched successfully
    }
    is PlayerLaunchResult.Failure -> {
        // Handle failure: result.message
    }
}
```

#### Variant 2: With Feed Configuration

Launch the player with a feed configuration.

**Signature:**

```kotlin
fun startPlayer(
    viewOptions: ViewOptions
): PlayerLaunchResult
```

**Parameters:**

* `viewOptions` - Player and feed configuration options

**Returns:** `PlayerLaunchResult` indicating success or failure

**Example:**

```kotlin
val viewOptions = viewOptions {
    baseOptions {
        feedResource(FeedResource.Discovery)
    }
    playerOptions {
        showShareButton(true)
        enablePipMode(true)
    }
}

when (val result = FireworkSdk.startPlayer(viewOptions)) {
    is PlayerLaunchResult.Success -> {
        // Player launched successfully
    }
    is PlayerLaunchResult.Failure -> {
        // Handle failure: result.message
    }
}
```

**See Also:** [Open Fullscreen Player Guide](/firework-for-developers/android-sdk/integration-guide/fullscreen-player.md)

### closeFullScreenPlayer()

Closes the currently running full-screen player.

This method programmatically closes the full-screen player Activity launched by the Firework SDK.\
When invoked, it triggers a close event that all running player Activities listen to and respond\
by executing a graceful shutdown process.

**Signature:**

```kotlin
fun closeFullScreenPlayer()
```

**Example:**

```kotlin
// Close the player when user logs out
 fun onUserLogout() {
     FireworkSdk.closeFullScreenPlayer()
     // Perform other logout logic
 }

 // Close the player when app goes to background
 override fun onPause() {
     super.onPause()
     if (shouldClosePlayerOnBackground) {
         FireworkSdk.closeFullScreenPlayer()
     }
 }
```

***

## Shopping Features

### shopping

Access shopping-related functionality and callbacks.

**Type:** `Shopping` object

**Available Methods:**

* `setOnCtaButtonClickListener()` - Handle CTA button clicks
* `setOnCartClickListener()` - Handle shopping cart clicks
* `setOnProductHydrationListener()` - Hydrate product data
* `setOnProductLinkClickListener()` - Handle product link clicks
* `setOnProductCardClickListener()` - Handle product card clicks
* `setOnShoppingErrorListener()` - Handle shopping errors
* `setCartBehaviour()` - Configure cart behavior
* `setShoppingViewOptions()` - Customize shopping UI
* `trackPurchase()` - Track purchase events

**Example:**

```kotlin
// Handle CTA button clicks
FireworkSdk.shopping.setOnCtaButtonClickListener { url, videoInfo ->
    // Open product page
    openUrl(url)
}

// Configure cart behavior
FireworkSdk.shopping.setCartBehaviour(CartBehaviour.Embedded)

// Track purchase
FireworkSdk.shopping.trackPurchase(
    productId = "product123",
    price = 29.99,
    currency = "USD"
)
```

**See Also:** [Shopping Integration Guide](/firework-for-developers/android-sdk/integration-guide/shoppable-videos.md)

***

## Livestream Features

### livestream

Access livestream-related functionality and callbacks.

**Type:** `Livestream` object

**Available Methods:**

* `setOnLinkClickListener()` - Handle link clicks in livestream
* `setOnInteractionListener()` - Handle polls, questions, and giveaways
* `setOnGiveawayTermsAndConditionsClickListener()` - Handle T\&C clicks
* `setOnUpdateUsernameListener()` - Handle username updates
* `updateUsername()` - Update user's display name
* `getUsername()` - Get current username
* `updateUsernameConfiguration()` - Configure username settings

**Example:**

```kotlin
// Handle link clicks
FireworkSdk.livestream.setOnLinkClickListener { link ->
    openUrl(link)
    true // Return true if handled
}

// Handle interactions
FireworkSdk.livestream.setOnInteractionListener { interaction ->
    when (interaction) {
        is QuestionInteraction -> {
            // Handle question
        }
        is PollInteraction -> {
            // Handle poll
        }
        is GiveawayInteraction -> {
            // Handle giveaway
        }
    }
}

// Update username
FireworkSdk.livestream.updateUsername(
    username = "JohnDoe",
    onSuccess = {
        // Username updated successfully
    },
    onError = { error ->
        // Handle error
    }
)
```

**See Also:** [Livestream Integration](/firework-for-developers/android-sdk/integration-guide/livestream.md)

***

## Picture-in-Picture (PIP)

### isInPip

Check if the player is currently in PIP mode.

**Type:** `Boolean` property

**Example:**

```kotlin
if (FireworkSdk.isInPip) {
    // Player is in PIP mode
}
```

### enterPip()

Enter Picture-in-Picture mode programmatically.

**Signature:**

```kotlin
fun enterPip(
    onSuccess: ((alreadyInPipMode: Boolean) -> Unit)? = null,
    onError: ((PipEnterError) -> Unit)? = null
)
```

**Parameters:**

* `onSuccess` - Optional callback with boolean indicating if already in PIP
* `onError` - Optional callback invoked on PIP entry failure

**Example:**

```kotlin
FireworkSdk.enterPip(
    onSuccess = { alreadyInPip ->
        if (alreadyInPip) {
            // Already in PIP mode
        } else {
            // Successfully entered PIP mode
        }
    },
    onError = { error ->
        // Handle PIP entry error
    }
)
```

### closePip()

Close Picture-in-Picture mode and dismiss the player.

**Signature:**

```kotlin
fun closePip()
```

**Example:**

```kotlin
override fun onDestroy() {
    FireworkSdk.closePip()
    super.onDestroy()
}
```

***

## Player Versions

### setVideoPlayerVersion()

Set the version of the video player to use.

**Signature:**

```kotlin
fun setVideoPlayerVersion(playerVersion: FwVideoPlayerVersion)
```

**Parameters:**

* `playerVersion` - The video player version

**Available Values:**

* `FwVideoPlayerVersion.V1` - Video Player version 1
* `FwVideoPlayerVersion.V2` - Video Player version 2 (recommended)

**Example:**

```kotlin
// Use V2 player (recommended)
FireworkSdk.setVideoPlayerVersion(FwVideoPlayerVersion.V2)

// Call before SDK initialization
FireworkSdk.init(config)
```

### setLivestreamPlayerVersion()

Set the version of the livestream player to use.

**Signature:**

```kotlin
fun setLivestreamPlayerVersion(playerVersion: FwLivestreamPlayerVersion)
```

**Parameters:**

* `playerVersion` - The livestream player version

**Available Values:**

* `FwLivestreamPlayerVersion.V1` - Livestream Player version 1
* `FwLivestreamPlayerVersion.V2` - Livestream Player version 2 (recommended)

**Example:**

```kotlin
// Use V2 player (recommended)
FireworkSdk.setLivestreamPlayerVersion(FwLivestreamPlayerVersion.V2)

// Call before SDK initialization
FireworkSdk.init(config)
```

**Important:** Call player version setters before `FireworkSdk.init()`.

***

## Player Launch Mode

### setPlayerLaunchMode()

Configure the Android launch mode for the player activity.

**Signature:**

```kotlin
fun setPlayerLaunchMode(playerActivityLaunchMode: FwPlayerActivityLaunchMode)
```

**Parameters:**

* `playerActivityLaunchMode` - The launch mode to set

**Available Values:**

* `FwPlayerActivityLaunchMode.SINGLE_TASK` - Standard single task launch mode
* `FwPlayerActivityLaunchMode.SINGLE_INSTANCE` - Single instance for complete isolation
* `FwPlayerActivityLaunchMode.SINGLE_TASK_WITH_OWN_AFFINITY` - Single task with custom affinity

**Example:**

```kotlin
// Set single instance mode
FireworkSdk.setPlayerLaunchMode(FwPlayerActivityLaunchMode.SINGLE_INSTANCE)

// Then launch player
FireworkSdk.startPlayer(viewOptions)
```

***

## Tracking and Metrix

### setTrackingLevel()

Sets the level of data tracking.

**Signature:**

```kotlin
fun setTrackingLevel(trackingLevel: FwTrackingLevel)
```

**Parameters:**

* `FwTrackingLevel` - the level of data tracking to be set.

**Available Values:**

* `FwTrackingLevel.ALL` - Sends all analytic events
* `FwTrackingLevel.ESSENTIAL_ONLY` - Sends only the essential tracking events.
* `FwTrackingLevel.NONE` - Sends no tracking events

#### Notes:

Please note that if you set the `FwTrackingLevel` to `FwTrackingLevel.NONE`, data regarding users watching videos and livestreams will not be reported. This may negatively impact the data reports related to each video or livestream displayed in the Business Portal.

***

## API Summary Table

| API                            | Category       | Description                     |
| ------------------------------ | -------------- | ------------------------------- |
| `init()`                       | Initialization | Initialize the SDK              |
| `isSdkInitialized()`           | Initialization | Check SDK Initialization status |
| `startPlayer()`                | Player         | Launch fullscreen video player  |
| `closeFullScreenPlayer()`      | Player         | Close fullscreen video player   |
| `shopping`                     | Shopping       | Access shopping features        |
| `livestream`                   | Livestream     | Access livestream features      |
| `analytics`                    | Analytics      | Access analytics event bus      |
| `isInPip`                      | PIP            | Check if in PIP mode            |
| `enterPip()`                   | PIP            | Enter PIP mode                  |
| `closePip()`                   | PIP            | Close PIP mode                  |
| `setTrackingLevel()`           | Analytics      | Configure tracking level        |
| `setVideoPlayerVersion()`      | Player         | Set video player version        |
| `setLivestreamPlayerVersion()` | Player         | Set livestream player version   |
| `setPlayerLaunchMode()`        | Player         | Set player launch mode          |

## See Also

* [Getting Started](/firework-for-developers/android-sdk/integration-guide/getting-started.md) - SDK initialization and setup
* [Video Player Configuration](/firework-for-developers/android-sdk/integration-guide/video-player.md) - Player customization options
* [Shopping Integration](/firework-for-developers/android-sdk/integration-guide/shoppable-videos.md) - Shopping features and callbacks
* [Livestream Integration](/firework-for-developers/android-sdk/integration-guide/livestream.md) - Livestream features and callbacks
* [Configuration Guide](/firework-for-developers/android-sdk/integration-guide/configuration.md) - ViewOptions and customization
* [Analytics](/firework-for-developers/android-sdk/integration-guide/analytics.md) - About listen to analytics event from Firework SDK


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.firework.com/firework-for-developers/android-sdk/integration-guide/firework-sdk-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
