本文說明如何在 Android 應用程式中整合及自訂 Headless Mobile SDK。內容涵蓋智慧操作、附件和轉移。
。設定智慧動作和附件
代理商和消費者可透過智慧動作交換豐富的結構化資訊,例如相片、影片、文字片段和生物特徵辨識驗證。
在無頭架構中,SDK 嚴格來說是安全傳輸層。這項服務會通知您何時需要或要求採取行動,並安全地將資料傳輸至 CCAI Platform 平台。由於您擁有使用者介面,因此應用程式必須負責建構相機畫面、相片挑選器、文字方塊,以及觸發 Android 內建的生物特徵辨識提示。
工作階段前智慧操作
在使用者加入佇列前,預先工作階段動作會收集相關資訊 (例如帳號或產品故障的影片),大幅縮短服務專員的處理時間。
SDK 提供的資訊:特定佇列的規則和規定 (例如加入佇列前是否必須通過生物辨識驗證、上傳相片或輸入文字)。
建構內容:使用者輕觸佇列並進入等候室之間顯示的會前使用者介面畫面 (攝影機、文字輸入和生物特徵辨識提示),以及磁碟快取邏輯,可安全地保留媒體,直到連線至工作階段為止。
導入範例
這段程式碼會檢查 SDK 的設定,確認所選佇列是否符合會前需求。這項範例說明如何處理影片需求,方法是在磁碟上保留檔案 Uri 參照,而非將影片保留在記憶體中。
// 1. Check requirements and collect data BEFORE joining the queue
fun checkPreSessionRequirements(queueMenu: QueueMenu) {
val smartActions = queueMenu.settings
if (smartActions.isNullOrEmpty()) {
startChat(queueMenu)
return
}
// Example: handle a video requirement
presentVideoPicker { localFileUri ->
// IMPORTANT: localFileUri should point to context.cacheDir
MySessionStateManager.pendingPreSessionVideo = localFileUri
startChat(queueMenu)
}
}
// 2. Upload and clean up AFTER the session officially connects
fun handleSessionConnected() {
val pendingVideoUri = MySessionStateManager.pendingPreSessionVideo ?: return
// Upload using the standard in-session pipeline
// then clean up the temporary file
val file = File(pendingVideoUri.path ?: return)
file.delete()
MySessionStateManager.pendingPreSessionVideo = null
}
讀取會前智慧動作設定
SDK 會透過兩種互補路徑,公開會前智慧動作設定。請查看這兩者,判斷特定佇列和管道是否需要會前擷取。
路徑 A - 佇列層級 (QueueMenu.settings[].sdk.preSessionSmartAction)
// `QueueMenuSetting` and `QueueMenuSDKSetting` (simplified)
data class QueueMenuSetting(
val sdk: QueueMenuSDKSetting?
// ... other fields ...
)
data class QueueMenuSDKSetting(
val preSessionSmartAction: Boolean?
// ... other fields ...
)
// Usage - "does any queue-level setting require a pre-session smart action?"
fun queueRequiresPreSession(menu: QueueMenu): Boolean {
return menu.settings?.any { it.sdk?.preSessionSmartAction == true } ?: false
}
路徑 B - 管道層級 (VoiceCallChannel.preSessionSmartAction)
// Usage - "does the voice channel specifically require pre-session capture?"
val requiresPreSessionOnVoice =
menu.channels.voiceCall?.preSessionSmartAction == true
使用「路徑 A」決定是否在使用者選擇頻道前顯示會前閘道。選取管道後,如要進行管道專屬的微調 (例如只在即時語音通話前提示),請使用「路徑 B」。
工作階段內智慧操作 (由服務專員發起)
在進行中的即時通訊或語音通話中,服務專員可以點選資訊主頁上的按鈕,向使用者索取資料 (例如「傳送身分證件相片」或「使用生物特徵辨識驗證」)。
SDK 提供內容:即時事件,可提醒應用程式代理程式已要求特定類型的智慧動作。
建構內容:在即時通訊或通話中顯示警示,通知使用者要求、啟動適當的內建工具 (相機、相片庫、文字欄位或 Android BiometricPrompt),並將結果傳回 SDK。
導入範例
在此,您的應用程式會監聽 SDK 事件。偵測到代理要求時,會顯示快訊,然後開啟適當的 Android 工具。
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
// Listen for Smart Action requests from the active SDK session.
//
// `SmartActionRequest` exposes a nested `smartAction: SmartAction`, and the
// switchable type lives at `request.smartAction.type`. The `SmartActionType`
// enum is `PascalCase: Unknown`, `Verification`, `Screenshot`, `Photo`, `Video`,
// `TextInput`, `ScreenShare`. Use `Verification` for Face ID / fingerprint flows.
fun handleSmartActionRequest(request: SmartActionRequest) {
when (request.smartAction.type) {
SmartActionType.Photo -> {
promptUserForPhoto(message = "The agent requested a photo.") { capturedBitmap ->
// Send the image back to the agent using the SDK.
sendAttachment(image = capturedBitmap)
}
}
SmartActionType.Verification -> {
val executor = ContextCompat.getMainExecutor(this)
val biometricPrompt = BiometricPrompt(this, executor,
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(
result: BiometricPrompt.AuthenticationResult
) {
sendBiometricResult(success = true)
}
override fun onAuthenticationFailed() {
sendBiometricResult(success = false)
}
override fun onAuthenticationError(
errorCode: Int, errString: CharSequence
) {
sendBiometricResult(success = false)
}
}
)
val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Identity Verification")
.setSubtitle("Verify your identity to continue")
.setNegativeBtnText("Cancel")
.build()
biometricPrompt.authenticate(promptInfo)
}
SmartActionType.TextInput -> {
presentTextInputPrompt(message = "The agent requested text input.") { text ->
sendSmartActionText(text)
}
}
SmartActionType.Video -> {
// Agent-requested video capture. Reuse the same disk-cached file
// pattern recommended for pre-session media keep the recording on
// disk and pass the local Uri to the SDK rather than holding a
// large `ByteArray` in memory.
promptUserForVideo(message = "The agent requested a video.") { capturedVideoUri ->
sendAttachment(videoUri = capturedVideoUri)
}
}
SmartActionType.Screenshot -> {
// The SDK exposes `Screenshot` as a distinct request type the
// user captures (or selects), a single still image of the current
// screen. This is **not** the same as `ScreenShare`, which
// starts a live co-browse session.
promptUserForScreenshot(message = "The agent requested a screenshot.") { capturedBitmap ->
sendAttachment(image = capturedBitmap)
}
}
SmartActionType.ScreenShare -> {
// Hand off to the full screen share flow (see Headless Mobile SDK for Android: Voice, screen share, scheduled call, and email).
// Don't confuse with `Screenshot`; `ScreenShare` starts a
// live co-browse session using `CCAIScreenShare`, while `Screenshot`
// captures a single still frame.
startScreenShareFlow()
}
SmartActionType.Unknown -> {
// Future-proof: a smart action type the SDK does not recognize.
// Log and continue; don't block the user.
Log.w("CCAI", "Received unknown smart action type")
}
}
}
系統會透過有效工作階段的 SDK 事件,傳送代理發起的智慧動作。開始工作階段前,請先訂閱相關的即時通訊或通話事件,這樣應用程式就能在收到要求時,立即向顧客顯示適當的提示。
通知及追蹤智慧操作
當使用者完成智慧動作時,請使用 smartActionService 確認並更新智慧動作。
val router = CommunicationRouter(
id = chatId,
type = CommunicationType.Chat
)
// Notify the server that a smart action has been received.
lifecycleScope.launch {
try {
CCAI.smartActionService?.notifySmartActionReceived(
router = router,
smartActionId = smartActionId
)
Log.d("CCAI", "Smart action notification sent successfully")
} catch (e: Exception) {
Log.e("CCAI", "Failed to notify smart action: ${e.message}")
}
}
// Update the smart action status as the user completes it.
lifecycleScope.launch {
try {
CCAI.smartActionService?.updateSmartActionStatus(
router = router,
smartActionId = smartActionId,
status = SmartActionStatus.Finished
)
Log.d("CCAI", "Smart action status updated successfully")
} catch (e: Exception) {
Log.e("CCAI", "Failed to update smart action status: ${e.message}")
}
}
如果動作要求輸入文字,請在 UI 中收集文字,然後透過智慧動作服務傳送文字,再將動作標示為完成。
線上表單
SDK 提供哪些功能:在即時通訊期間,提供 API 來擷取、顯示及驗證代理觸發的網路表單。
建構內容:網頁表單轉譯 UI 和提交流程,可將使用者的回覆封裝。
導入範例
這段程式碼會依據外部 ID 和智慧動作 ID 擷取網路表單,然後在提交前驗證回覆。
// Fetch a web form - `fetchWebForm` takes two positional parameters on Android.
lifecycleScope.launch {
try {
val webFormResponse = CCAI.chatService?.fetchWebForm(
externalFormId = "form123",
smartActionId = 123
)
if (webFormResponse != null) {
Log.d("CCAI", "Web form received: $webFormResponse")
// Render the web form in your custom UI.
renderWebForm(webFormResponse)
}
} catch (e: Exception) {
Log.e("CCAI", "Failed to fetch web form: ${e.message}")
}
}
// Validate a web form response.
lifecycleScope.launch {
try {
val isValid = CCAI.chatService?.validateWebForm(webFormResponse)
if (isValid == true) {
Log.d("CCAI", "Web form is valid")
} else {
Log.d("CCAI", "Web form validation failed")
}
} catch (e: Exception) {
Log.e("CCAI", "Failed to validate web form: ${e.message}")
}
}
自訂表單
SDK 提供哪些功能:API 可擷取可設定的表單定義 (包含多種問題類型),並提交使用者的答案。
建構內容:動態表單 UI,可算繪各類問題 (文字欄位、下拉式選單等)、驗證輸入內容,以及收集回覆以供提交。
導入範例
這段程式碼會擷取自訂表單的問題定義,然後封裝並提交使用者的答案。
// Retrieve custom form details
lifecycleScope.launch {
try {
val formDetails = CCAI.chatService?.getCustomFormDetails(formId = 123)
if (formDetails != null) {
Log.d("CCAI", "Form Title: ${formDetails.title ?: "No title"}")
Log.d("CCAI", "Questions: ${formDetails.questions.size}")
// Render the form dynamically based on question types
renderCustomForm(formDetails)
}
} catch (e: Exception) {
Log.e("CCAI", "Failed to get custom form details: ${e.message}")
}
}
// Submit a custom form
val request = SubmitCustomFormRequest(
smartActionId = 123,
formResponse = listOf(
SubmitCustomFormRequest.Answer(questionId = 1, value = "John Doe"),
SubmitCustomFormRequest.Answer(questionId = 2, value = "john@example.com")
)
)
lifecycleScope.launch {
try {
CCAI.chatService?.submitCustomForm(request = request)
Log.d("CCAI", "Form submitted successfully")
} catch (e: Exception) {
Log.e("CCAI", "Failed to submit form: ${e.message}")
}
}
如要查看完整的 CustomFormDetailsResponse、CustomFormQuestion、CustomFormQuestionOption 和 CustomFormQuestionType 列舉定義,請參閱「無頭行動版 SDK - Android API 參考資料」。
消費者發起的附件 (即時通訊)
使用者不必等待服務專員詢問,可以在即時通訊期間主動傳送圖片和影片。SDK 會強制執行嚴格的檔案大小限制,並在傳輸前自動嘗試壓縮檔案。
附件大小限制
圖片:≤ 2 MB
影片:≤ 20 MB
SDK 提供哪些功能:安全的上傳管道,可處理網路傳輸作業,並自動壓縮檔案,以符合 CCAI 平台的限制。
建構內容:即時通訊使用者介面中的迴紋針 / 附件按鈕、相片/影片挑選器,以及顯示上傳狀態 (載入中、已傳送或失敗) 的視覺化即時通訊泡泡。
導入範例
使用者從相簿選取相片或影片後,請使用與所有外寄訊息相同的 sendMessage API,將本機檔案 Uri 傳遞至 SDK。詳情請參閱「傳送訊息」。
SDK 會負責壓縮及上傳。
// Called when the user picks an image from their photo gallery
fun userDidSelectImage(imageUri: Uri) {
val messageBubble = myChatAdapter.addLoadingImageBubble()
lifecycleScope.launch {
try {
CCAI.chatService?.sendMessage(
OutgoingMessageContent.Photos(
images = listOf(imageUri),
smartAction = null
)
)
messageBubble.markAsSent()
} catch (e: Exception) {
messageBubble.showError("Failed to send: ${e.message}")
}
}
}
服務專員發起的附件 (即時通訊)
代理程式可以將檔案傳回給使用者,包括圖片、影片、音訊片段和文件 (PDF、CSV 等)。
支援的檔案類型
CCAI 平台接受四種類別的 19 種檔案類型。自訂 UI 應妥善處理每個類別 (圖片預覽、影片播放器、音訊播放器、文件下載)。
| 類別 | 支援的類型 |
|---|---|
| 圖片 | JPEG、PNG、GIF 和 WebP。 |
| 影片 | MP4、MOV、AVI、WMV 和 WebM。 |
| 音訊 | MP3、WAV、M4A 和 WEBA。 |
| 文件 | PDF、DOC、XLS、PPT、CSV 和 TXT。 |
SDK 提供哪些功能:使用即時通訊服務的訊息 Flow 傳送的即時通訊訊息酬載,其中包含附件中繼資料。詳情請參閱「Android 無標題行動 SDK:進階主題、本地化和會後流程」。即時通訊服務也提供 downloadMedia
,可安全地擷取代理程式傳送的媒體。
您要建構的內容:在聊天室訊息串中顯示這些附件的 UI。應用程式會決定是否顯示圖片預覽、影片縮圖、音訊播放控制項或文件下載按鈕。
導入範例
使用即時通訊服務的訊息 Flow 觀察傳入的訊息。如果新訊息包含媒體中繼資料,請在算繪或開啟檔案前呼叫 downloadMedia。
downloadMedia 會傳回 DownloadMediaResponse { data: ByteArray, fileName:
String? },也就是完全下載的位元組,以及選用的顯示檔案名稱。SDK 不會快取下載內容。如果 UI 捲動回舊訊息泡泡或重新進入對話檢視畫面,應用程式必須負責快取已解碼的圖片或保存位元組;再次呼叫 downloadMedia 會觸發另一次網路擷取作業。
import android.graphics.BitmapFactory
import java.io.File
lifecycleScope.launch {
CCAI.chatService?.messagesReceived?.collect { messages ->
for (message in messages) {
renderIncomingMessage(message)
}
}
}
fun renderIncomingMessage(message: ChatMessage) {
val media = message.media
if (media == null) {
myChatAdapter.insertTextBubble(text = message.text)
return
}
lifecycleScope.launch {
try {
// `downloadMedia` returns the raw bytes plus an optional filename.
val response = CCAI.chatService?.downloadMedia(
mediaId = media.id,
mediaType = media.type
) ?: return@launch
when (media.type) {
DownloadableMediaType.Photo -> {
// Decode in-memory; no disk write needed.
val bitmap = BitmapFactory.decodeByteArray(
response.data, 0, response.data.size
)
myChatAdapter.insertImageBubble(
bitmap = bitmap,
fileName = response.fileName
)
}
DownloadableMediaType.Video,
DownloadableMediaType.Audio,
DownloadableMediaType.Document -> {
// Larger media usually needs an on-disk file for a player
// or document viewer. Write to the app's cache directory
// yourself and hand the resulting File/Uri to your UI.
val file = File(
applicationContext.cacheDir,
response.fileName ?: "attachment"
)
file.writeBytes(response.data)
myChatAdapter.insertAttachmentBubble(
file = file,
mediaType = media.type
)
}
}
} catch (e: Exception) {
myChatAdapter.insertAttachmentErrorBubble(fileName = message.media?.name)
}
}
}
轉接 (下班時間和超出容量)
如果支援團隊無法提供服務,系統會將使用者重新導向至其他頁面。這通常發生在以下兩種情況:
非營業時間:使用者嘗試在設定的營業時間外聯絡支援團隊。
容量過高:佇列已開放,但等待時間超過管理員設定的門檻。
在無頭架構中,SDK 不會自動封鎖使用者或彈出錯誤畫面。而是會將轉移狀態和管理員設定的回退選項,悄悄傳遞至應用程式。應用程式必須先檢查這個狀態,再嘗試啟動工作階段。
處理轉移狀態
SDK 提供的內容:deflectionFrom: List<QueueMenuDeflection>?,列出將其他佇列的來電轉接規則轉送至這個佇列。QueueMenu每個 QueueMenuDeflection 只會攜帶兩個欄位:
deflectionType: DeflectionType?:轉接類別 (例如下班時間或超出容量)。menuId: Int?:將通話轉接至這個佇列的來源佇列 ID。
QueueMenuDeflection 未顯示訊息或使用者可解讀的標籤。如要顯示給使用者 (例如「本辦公室已關閉」),請使用佇列的 afterHoursMessage (衍生自 QueueMenu.settings[].afterHours) 或您自行設定的管理員字串。如要查看已解決目的地佇列的顯示名稱,請透過 menuId 從已擷取的選單樹狀結構中查詢。
建構內容:在將使用者加入佇列前,檢查這些轉移狀態的邏輯,以及顯示適當訊息和替代路徑按鈕的自訂 UI (例如全螢幕警示或橫幅)。
導入範例
下方程式碼會攔截使用者嘗試發起對話的行為。這項功能會檢查 QueueMenu 上的 SDK 轉移中繼資料,如果規則有效,就會使用佇列的 afterHoursMessage (或備援) 顯示轉移畫面。
fun onSupportMenuTapped(queueMenu: QueueMenu) {
// 1. Check if any deflection rules route into this queue.
val deflections = queueMenu.deflectionFrom
if (!deflections.isNullOrEmpty()) {
// Deflection is active - stop routing. Show the custom deflection screen instead.
val message = queueMenu.afterHoursMessage?.text
?: "Support is currently unavailable."
showDeflectionScreen(
message = message,
deflections = deflections
)
} else {
// No deflection rules apply. Safe to proceed to channel selection or directly to chat/call.
startSupportFlow(queueMenu)
}
}
算繪偏轉選項
啟用轉移規則後,管理員可能會設定其他方式,讓使用者取得協助,通常是轉移至其他佇列 (您可以使用 menuId 解決問題),或是顯示目前佇列設定的 afterHoursMessage。
SDK 提供的內容:QueueMenuDeflection 上的項目清單,每個項目都有 deflectionFrom 和 deflectionType。menuId
建構內容:動態選單,會逐一檢查這些項目、針對已擷取的選單樹狀結構解析每個 menuId,取得顯示名稱,並產生適當的按鈕。
導入範例
這段程式碼會取得轉向項目,並動態建構畫面。系統會使用來源佇列的名稱 (從 menuId 解析) 做為按鈕標籤,如果沒有名稱,則會改用 deflectionType。
fun showDeflectionScreen(message: String, deflections: List<QueueMenuDeflection>) {
// 1. Update your UI with the admin's configured message (or your fallback).
deflectionTitleTextView.text = message
// 2. Loop through the incoming deflection rules and generate buttons.
for (deflection in deflections) {
val sourceMenu = deflection.menuId?.let { findMenuById(it) }
val label = sourceMenu?.name
?: deflection.deflectionType?.name
?: "Alternative option"
val button = MaterialButton(this).apply {
text = label
setOnClickListener {
handleDeflectionAction(deflection)
}
}
menuLinearLayout.addView(button)
}
// 3. Present the compiled screen to the user.
deflectionContainer.isVisible = true
}
// Walk your previously fetched menu tree (for example, by using `QueueMenu.flatten()`) to resolve a `menuId`.
private fun findMenuById(id: Int): QueueMenu? =
cachedRootMenus.flatMap { it.flatten() }.firstOrNull { it.id == id }
deflectionFrom 是導向這個選單的轉移規則清單,每個項目都以 menuId 標示,代表轉移至目前佇列的來源佇列。應用程式會決定如何公開這些內容。部分整合功能會將目的地佇列顯示為「這裡會改為傳送給你」,而其他功能則只會使用任何規則的存在做為閘道,顯示一般「稍後再試」畫面。