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

# 移动端 SDK - Android

**仓库：** [https://github.com/KlipFit/kleep-android](https://github.com/KlipFit/kleep-android)

## 安装

***

此流程仅需执行一次，即首次在项目中安装 SDK 时。后续更新请参阅 **Update** 部分的说明。

1. 在您的 *gradle.properties* 中添加以下 token：

   `authToken=jp_9ibcequhrjtge3cmavt2k4sq6a`

2. 在您的 *settings.gradle 或 settings.gradle.kts* 中添加以下内容：

```groovy theme={null}
// for *settings.gradle*

dependencyResolutionManagement {
*// ...*
    repositories {
        *// ...*
~~~~        maven {
            url "https://jitpack.io"
            credentials { username authToken }
        }
    }
}
```

```kotlin theme={null}
// for *settings.gradle.kts*

*dependencyResolutionManagement {
// ...
    repositories {
	      // ... 
        maven {
            url = uri("https://jitpack.io")
            credentials(PasswordCredentials::class) {
                val authToken: String by settings
                username = authToken*
            }
        *}
    }
}*
```

1. 在您模块的 *build.gradle* 或 *build.gradle.kts* 文件中添加以下内容以创建依赖：

```groovy theme={null}
// *build.gradle*
dependencies {
	implementation 'com.github.KlipFit:kleep-android:version'
}
```

```kotlin theme={null}
// *build.gradle.kts*
dependencies {
	implementation("com.github.KlipFit:kleep-android:version")
}
```

## **初始化**

***

编辑您自定义的 `Application` 类，并提供 `applicationContext` 进行初始化。

```kotlin theme={null}
import com.kleep.sdk.KleepResult
import com.kleep.sdk.Kleep

class CustomApplication: Application() {

    override fun onCreate() {
        super.onCreate()
        Kleep.init(applicationContext)
    }
}
```

请勿忘记将您的 Application 类添加至 **`Manifest.xml`**

```kotlin theme={null}
<application
        android:name=".CustomApplication"
        ...
        >
...
</application>
```

## 导入

***

您可以在 **`MainActivity.kt`** 开头手动导入模块

```kotlin theme={null}
import com.kleep.sdk.KleepResult
import com.kleep.sdk.Kleep
```

## 使用方法

***

SDK 提供 3 个方法：

| method        | 加载时间                     |
| ------------- | ------------------------ |
| `show`        | 首次启动：250ms，后续启动：50-250ms |
| `requestSize` | 250ms                    |
| `track`       | 250ms                    |

### 方法 1：`requestSize`

此方法用于实现 CTA 的逻辑。

**逻辑图示**

此图示说明如何更新打开 Kleep 的 CTA。

[https://www.figma.com/board/BlurZ01lR3JBQZeTUU98TE/Mobile---CTA-Logic?node-id=0-1\&t=ccXWciNziIdfhgew-1](https://www.figma.com/board/BlurZ01lR3JBQZeTUU98TE/Mobile---CTA-Logic?node-id=0-1\&t=ccXWciNziIdfhgew-1)

**实现示例**

```kotlin theme={null}
Kleep.builder(this, onResult = {
	when (it) {
	    is KleepResult.NotSupported -> {
	        // Handle the NotSupported case
	    }
	
	    is KleepResult.NoRecommendationYet -> {
	        // Handle the NoRecommendationYet case
	    }
	
	    is KleepResult.RecommendationFound -> {
	        val resultText = it.size
	        val variantId = it.variantId
	        Toast.makeText(this, resultText, Toast.LENGTH_SHORT).show()         
      }

      else -> {

      }
    }
})
	.setPackageName(packageName)         // optional
	.setLang(DEFAULT_LANGUAGE)           // required: "fr", "en", "es", "it", "pt", "nl"
	.setProductId("1234")                // required
	.setRetailer("retailer_name")        // required
	.setTrackingId("uuid")               // empty if non-existent 
	.setCustomerId("unique_customer_id") // optional
	.requestSize()
```

```kotlin theme={null}
package com.kleep.sdk

/**
 * Interface with the Kleep SDK in order to compute the recommended size of a product given some user information
 */
interface KleepDialogBuilder {
    /**
     * Set the package name, not required
     * @return interface of the SDK builder
     */
    fun setPackageName(packageName: String): KleepDialogBuilder
    
    /**
     * Set the language to use: required (default to FR)
     * Values supported: "fr", "en", "es", "it", "pt", "nl"
     * @return interface of the SDK builder
     */
    fun setLang(lang: String): KleepDialogBuilder

    /**
     * Set product ID, required to compute the recommended size.
     * @return interface of the SDK builder
     */
    fun setProductId(productId: String): KleepDialogBuilder

    /**
     * Set tracking id, required. Should represent unique tracking id.
     * Should be an empty string if the tracking id does not exist.
     *
     * @return interface of the SDK builder
     */
    fun setTrackingId(tracking_id: String): KleepDialogBuilder

    /**
     * Set customer id, optonal. Should represent customer id linked to backend.
     * Should be an empty string if the tracking id does not exist.
     *
     * @return interface of the SDK builder
     */
    fun setCustomerId(customer_id: String): KleepDialogBuilder
    
    /**
     * Set retail name (mandatory), required for stock/similar_products requests.
     *
     * @return interface of the SDK builder
     */
    fun setRetailer(retailerName: String): KleepDialogBuilder
    
    /**
     * Sets the stock availability for items.
     * Providing an empty map or omitting this function disables stock checking.
     *
     * @return interface of the SDK builder
     */
    fun setStocks(stocks: Map<String, Boolean>): KleepDialogBuilder

    /**
     * Display the Kleep UI inside a BottomSheet, so the user can fill a survey or take 2 pictures
     * in order to compute and display the recommended size to the user
     */
    fun show()

    /**
     * Get the latest recommended size for the last viewed user.
     * As it's an async process and take several seconds,
		 * the result will be give by the onResult listener , provided to the SDK builder
     */
    fun requestSize()
}
```

### 方法 2：`show`

此方法在点击 CTA 时调用，用于加载各个界面。**集成 SDK 的开发者应将其嵌入底部弹窗（bottom sheet）中。**

| parameter      | priority | description                                                     |
| -------------- | -------- | --------------------------------------------------------------- |
| **productID**  | *必填*     | 您的产品 ID                                                         |
| **retailer**   | *必填*     | 零售商名称                                                           |
| **customerID** | *可选*     | CRM 标识符，用于分析                                                    |
| **trackingID** | *可选*     | 外部追踪服务使用的 ID                                                    |
| stocks         | *可选*     | 商品变体 ID 与库存状态的映射。`true` 表示有货，`false`（默认）表示缺货，传空 Map 或不传则跳过库存检查。 |

```kotlin theme={null}
Kleep.builder(this, onResult = {
	when (it) {
	    is KleepResult.NotSupported -> {
	        // Handle the NotSupported case
	    }
	
	    is KleepResult.NoRecommendationYet -> {
	        // Handle the NoRecommendationYet casem
	    }
	
	    is KleepResult.RecommendationFound -> {
	        val resultText = it.size
	        val variantId = it.variantId
	        // addToCart(variantId)
	        
	        Toast.makeText(this, resultText, Toast.LENGTH_SHORT).show()
      }

      else -> {

      }
    }
})
	.setPackageName(packageName)         // optional
	.setLang(DEFAULT_LANGUAGE)           // required: "fr", "en", "es", "it", "pt", "nl"
	.setProductId("1234")                // required
	.setRetailer("retailer_name")        // required
	.setTrackingId("tracking_id")        // optional
	.setCustomerId("unique_customer_id") // optional
	.setStocks(stocks: Map<String, Boolean>) // optional
	.show()
```

### 方法 3：`track`

此方法用于追踪自定义事件。

```kotlin theme={null}
Kleep.track(eventName: String, eventInfo: Map<String, String>)
```

我们需要追踪 3 个事件：

| eventName               | 触发时机         |
| ----------------------- | ------------ |
| `product_viewed`        | 查看商品详情页时     |
| `product_added_to_cart` | 商品加入购物车时     |
| `checkout_completed`    | 支付完成后收到订单确认时 |

**`product_viewed`**

[参数（CSV）](/images/android/Untitled%202c68bfd3e84981db82a9f924cf43673d.csv)

**示例**

```jsx theme={null}
{
		productId: str
}
```

**`product_added_to_cart`**

[参数（CSV）](/images/android/Untitled%202c68bfd3e8498100baf9d17e8b7df5e0.csv)

**示例**

```jsx theme={null}
{
    productId: str,
    variantId: str,
    cart: [
	    {
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
				sku: "XYZ",
		    size: "S",
		    quantity: 2,
		    price: {
						amount: "50",
				    currencyCode: "EUR"		    
		    }
	    },
	    {
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
		    sku: "XYZ",
		    size: "S",
		    quantity: 1,
		    price: {
				    amount: "40",
				    currencyCode: "USD"
				}
	    }
	    ...
    ],
}
```

**`checkout_completed`**

[参数（CSV）](/images/android/Untitled%202c68bfd3e84981b0bdecd417ba621e4e.csv)

**示例**

```jsx theme={null}
{
    orderId: "000001",
    cart: [
	    {
		    lineItemId: "000001#1",
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
				sku: "XYZ",
		    size: "S",
		    quantity: 2,
		    price: {
						amount: "50",
				    currencyCode: "EUR"		    
		    }
	    },
	    {
			  lineItemId: "000000#2",
		    productId: "123ABC456",
		    variantId: "123ABC456-00R",
		    sku: "XYZ",
		    size: "S",
		    quantity: 1,
		    price: {
				    amount: "40",
				    currencyCode: "USD"
				}
	    }
	    ...
    ],
}
```
