> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bit2connect.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Android SDK

> Integrate Bit2Connect dynamic links into your Android applications

## Installation

### Gradle

Add the Bit2Connect Android SDK to your app's `build.gradle`:

```kotlin theme={null}
dependencies {
    implementation 'com.bit2connect:sdk:1.0.0'
}
```

### Maven

If you're using Maven, add the dependency to your `pom.xml`:

```xml theme={null}
<dependency>
    <groupId>com.bit2connect</groupId>
    <artifactId>sdk</artifactId>
    <version>1.0.0</version>
</dependency>
```

## Setup

### 1. Initialize the SDK

Initialize the SDK in your Application class:

```kotlin theme={null}
import com.bit2connect.sdk.Bit2ConnectSDK

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

        // Initialize Bit2Connect SDK
        Bit2ConnectSDK.initialize(
            context = this,
            apiKey = "b2co_your_api_key_here",
            projectId = "your_project_id"
        )
    }
}
```

Don't forget to register your Application class in your `AndroidManifest.xml`:

```xml theme={null}
<application
    android:name=".MyApplication"
    ... >
    <!-- Your activities -->
</application>
```

### 2. Configure Deep Link Handling

Add deep link handling to your main activity:

```kotlin theme={null}
import com.bit2connect.sdk.Bit2ConnectSDK
import com.bit2connect.sdk.models.DynamicLinkData

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

        // Handle initial link if app was launched from a dynamic link
        handleInitialLink()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        handleIncomingLink()
    }

    private fun handleInitialLink() {
        val initialLink = Bit2ConnectSDK.getInitialLink(intent)
        initialLink?.let { linkData ->
            processDynamicLink(linkData)
        }
    }

    private fun handleIncomingLink() {
        val linkData = Bit2ConnectSDK.getLinkFromIntent(intent)
        linkData?.let { data ->
            processDynamicLink(data)
        }
    }

    private fun processDynamicLink(linkData: DynamicLinkData) {
        // Handle the dynamic link data
        Log.d("Bit2Connect", "Received link: ${linkData.shortUrl}")
        Log.d("Bit2Connect", "Original URL: ${linkData.originalUrl}")

        // Navigate to appropriate screen based on link data
        linkData.payload?.let { payload ->
            navigateToContent(payload)
        }
    }

    private fun navigateToContent(payload: Map&lt;String, Any&gt;) {
        // Implement your navigation logic here
        // Example: Navigate to a specific product page
        payload["productId"]?.let { productId ->
            val intent = Intent(this, ProductActivity::class.java)
            intent.putExtra("productId", productId.toString())
            startActivity(intent)
        }
    }
}
```

### 3. Configure Android Manifest

Add the following to your `AndroidManifest.xml`:

```xml theme={null}
<activity
    android:name=".MainActivity"
    android:exported="true"
    android:launchMode="singleTop"
    android:theme="@style/LaunchTheme">

    <!-- Existing intent filters -->

    <!-- Bit2Connect dynamic link intent filter -->
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https"
              android:host="bit2.co" />
    </intent-filter>
</activity>
```

## API Reference

### Bit2ConnectSDK

The main SDK class for handling dynamic links.

#### Methods

##### `initialize(context: Context, apiKey: String, projectId: String)`

Initialize the Bit2Connect SDK with your API credentials.

**Parameters:**

* `context` (Context): Application context
* `apiKey` (String): Your Bit2Connect API key
* `projectId` (String): Your project ID

**Example:**

```kotlin theme={null}
Bit2ConnectSDK.initialize(
    context = this,
    apiKey = "b2co_your_api_key_here",
    projectId = "your_project_id"
)
```

##### `getInitialLink(intent: Intent?): DynamicLinkData?`

Get the initial dynamic link that launched the app (if any).

**Parameters:**

* `intent` (Intent?): The intent that launched the activity

**Returns:** `DynamicLinkData?`

**Example:**

```kotlin theme={null}
val initialLink = Bit2ConnectSDK.getInitialLink(intent)
initialLink?.let { linkData ->
    // Process the initial link
}
```

##### `getLinkFromIntent(intent: Intent?): DynamicLinkData?`

Extract dynamic link data from an intent.

**Parameters:**

* `intent` (Intent?): The intent containing the link data

**Returns:** `DynamicLinkData?`

**Example:**

```kotlin theme={null}
val linkData = Bit2ConnectSDK.getLinkFromIntent(intent)
linkData?.let { data ->
    // Process the link data
}
```

##### `validateLink(url: String, callback: (Boolean, DynamicLinkData?) -> Unit)`

Validate a dynamic link URL.

**Parameters:**

* `url` (String): The dynamic link URL to validate
* `callback` (Function): Callback with validation result and link data

**Example:**

```kotlin theme={null}
Bit2ConnectSDK.validateLink("https://b2co.link/abc12345") { isValid, linkData ->
    if (isValid && linkData != null) {
        // Process valid link
    } else {
        // Handle invalid link
    }
}
```

### DynamicLinkData

Represents the data from a dynamic link.

#### Properties

* `shortUrl` (String): The shortened Bit2Connect URL
* `originalUrl` (String): The original URL that was shortened
* `payload` (Map\<String, Any>?): Custom data associated with the link
* `createdAt` (Date): When the link was created
* `expiresAt` (Date?): When the link expires (if applicable)

## Advanced Configuration

### Custom Link Handling

You can customize how links are processed by implementing a custom link handler:

```kotlin theme={null}
class CustomLinkHandler : LinkHandler {
    override fun handleLink(linkData: DynamicLinkData): Boolean {
        // Custom link processing logic
        when (linkData.payload?.get("type")) {
            "product" -> {
                // Handle product links
                return true
            }
            "category" -> {
                // Handle category links
                return true
            }
            else -> {
                // Let the SDK handle default processing
                return false
            }
        }
    }
}

// Register the custom handler
Bit2ConnectSDK.setLinkHandler(CustomLinkHandler())
```

### Analytics Integration

Track link performance and user engagement:

```kotlin theme={null}
class AnalyticsLinkHandler : LinkHandler {
    override fun handleLink(linkData: DynamicLinkData): Boolean {
        // Track link click
        analytics.track("dynamic_link_clicked", mapOf(
            "link_id" to linkData.id,
            "original_url" to linkData.originalUrl
        ))

        return false // Let default handler process the link
    }
}
```

## Testing

### Test Dynamic Links

You can test your integration using the Bit2Connect dashboard or API:

```kotlin theme={null}
// Test with a sample dynamic link
val testLink = "https://b2co.link/abc12345"
Bit2ConnectSDK.validateLink(testLink) { isValid, linkData ->
    if (isValid) {
        Log.d("Test", "Link is valid: ${linkData?.shortUrl}")
    } else {
        Log.e("Test", "Link is invalid")
    }
}
```

### Debug Mode

Enable debug logging to troubleshoot issues:

```kotlin theme={null}
Bit2ConnectSDK.initialize(
    context = this,
    apiKey = "b2co_your_api_key_here",
    projectId = "your_project_id",
    debugMode = true // Enable debug logging
)
```

## Best Practices

<CardGroup cols={2}>
  <Card title="Error Handling" icon="exclamation-triangle">
    Always handle potential errors when processing dynamic links
  </Card>

  <Card title="User Experience" icon="user">
    Provide fallback navigation for invalid or expired links
  </Card>

  <Card title="Security" icon="shield">
    Validate link data before processing to ensure security
  </Card>

  <Card title="Performance" icon="bolt">
    Cache link data when appropriate to improve app performance
  </Card>
</CardGroup>

## Troubleshooting

### Common Issues

<AccordionGroup>
  <Accordion title="Links not being received">
    **Solution:** Ensure your app is properly configured for deep linking and
    the SDK is initialized before handling links.
  </Accordion>

  <Accordion title="App not opening from links">
    **Solution:** Check that your Android manifest includes the correct intent
    filters and that your app is set as the default handler for Bit2Connect links.
  </Accordion>

  <Accordion title="Intent filters not working">
    **Solution:** Verify that your intent filters are correctly configured and
    that your app is properly signed.
  </Accordion>
</AccordionGroup>

### Debug Tips

1. Enable debug mode to see detailed logging
2. Test with the Bit2Connect dashboard link tester
3. Verify your app's deep link configuration
4. Check that your API key has the correct permissions
5. Use `adb` to test deep links: `adb shell am start -W -a android.intent.action.VIEW -d "https://b2co.link/abc12345" com.yourapp.package`

## Examples

### E-commerce App

```kotlin theme={null}
private fun processDynamicLink(linkData: DynamicLinkData) {
    val payload = linkData.payload

    when (payload?.get("type")) {
        "product" -> {
            val productId = payload["productId"] as? String
            productId?.let {
                val intent = Intent(this, ProductActivity::class.java)
                intent.putExtra("productId", it)
                startActivity(intent)
            }
        }
        "category" -> {
            val categoryId = payload["categoryId"] as? String
            categoryId?.let {
                val intent = Intent(this, CategoryActivity::class.java)
                intent.putExtra("categoryId", it)
                startActivity(intent)
            }
        }
        "promotion" -> {
            val promoCode = payload["promoCode"] as? String
            promoCode?.let {
                val intent = Intent(this, PromoActivity::class.java)
                intent.putExtra("promoCode", it)
                startActivity(intent)
            }
        }
    }
}
```

### Social Media App

```kotlin theme={null}
private fun processDynamicLink(linkData: DynamicLinkData) {
    val payload = linkData.payload

    when {
        payload?.containsKey("postId") == true -> {
            val postId = payload["postId"] as? String
            postId?.let {
                val intent = Intent(this, PostActivity::class.java)
                intent.putExtra("postId", it)
                startActivity(intent)
            }
        }
        payload?.containsKey("userId") == true -> {
            val userId = payload["userId"] as? String
            userId?.let {
                val intent = Intent(this, ProfileActivity::class.java)
                intent.putExtra("userId", it)
                startActivity(intent)
            }
        }
    }
}
```
