Android 專用的無頭行動 SDK:語音、螢幕分享、預約通話和電子郵件

本文說明如何在 Android 應用程式中整合及自訂 Headless Mobile SDK。包括語音、螢幕分享、預約通話和電子郵件。

語音通話

Android 版 Headless Mobile SDK 透過 CCAICall 和 CCAICallRed 模組提供語音通話支援。應用程式擁有自訂通話 UI,而 SDK 則負責處理通話建立、來電處理、供應商整合和通話生命週期狀態。

SDK 提供哪些功能:呼叫服務 API,用於發起即時通話、啟動語音信箱、處理來電及觀察通話狀態。

建構內容:視覺化通話體驗,包括通話前進入點、錄音同意提示、鈴聲或等待狀態、通話中控制項、前景服務 UI,以及任何通話後導覽。

初始化通話模組

初始化核心 SDK 後,請初始化通話模組:

import com.ccaiplatform.ccaikit.CCAI
import com.ccaiplatform.ccaicall.CallOptions
import com.ccaiplatform.ccaicall.initializeCall

CCAI.initialize(context = applicationContext, options = initOptions)

CCAI.initializeCall(
    context = applicationContext,
    options = CallOptions()
)

檢查 VoiceCallChannel 功能

提供即時通話服務前,請檢查佇列的 VoiceCallChannel,決定要公開哪些進入點 (即時通話、語音信箱備援、管道層級的轉移),以及是否需要錄音同意聲明。

重要VoiceCallChannel欄位

  • instantEnabled:Boolean - 這個佇列是否允許即時語音通話。將 false 視為「不提供即時通話按鈕」。與 voiceCall != null 不同,後者只會告知佇列有語音管道。

  • preSessionSmartAction:Boolean - 在開始通話前,這個特定管道是否需要會前智慧動作。如需互補的佇列層級路徑,請參閱「Android 無標題行動 SDK:智慧動作、附件和轉移」中的「會前智慧動作」。

  • scheduleEnabled:Boolean - 是否支援預約通話。請參閱「已排定的通話」部分。

  • recordingOption:RecordingOption? - 電話錄音同意聲明模型。請參閱「記錄同意聲明」。與 RecordingPermission.NOT_ASKED 不同,後者僅適用於預約通話。

  • voicemailReason:String? - 在管道設定為轉接至語音信箱時填入。

  • phoneNumber:String? - 為轉接或語音信箱設定的 PSTN 後備號碼。

  • scheduleDeflectionType:String? / deflected:Boolean? / deflectedReason:String? - 頻道層級的轉移中繼資料。當 deflected == true時,系統會顯示管理員設定的deflectedReason訊息,並提供設定的備援選項 (例如撥打電話號碼或預約通話的進入點),而不是嘗試立即通話。請參閱「等待時間轉移」一節。在 Android 適用的無頭行動 SDK 中:智慧動作、附件和轉移,適用於佇列層級的轉移處理。

fun voiceEntryPoints(menu: QueueMenu) {
    val voice = menu.channels.voiceCall
    if (voice == null) {
        callNowButton.isVisible = false
        voicemailButton.isVisible = false
        return
    }

    // Instant call - only when explicitly enabled and not deflected
    callNowButton.isVisible = voice.instantEnabled && voice.deflected != true

    // Voicemail fallback
    val number = voice.phoneNumber
    if (voice.voicemailReason != null && number != null) {
        voicemailButton.isVisible = true
        voicemailButton.text = "Leave a voicemail"
        voicemailButton.setOnClickListener {
            dialVoicemail(number, reason = voice.voicemailReason)
        }
    }

    // Channel-level deflection
    if (voice.deflected == true) {
        showChannelDeflection(reason = voice.deflectedReason)
    }
}

SDK 提供內容:VoiceCallChannel 上的 recordingOption:RecordingOption? 欄位,說明管理員在入口網站中設定的電話錄音同意聲明模式。

建構內容:同意提示 (在 ASK_USER 時) 和分支邏輯,可配合管理員的選擇。

enum class RecordingOption {
    ALWAYS,   // Calls are always recorded - surface a disclosure before connecting
    NEVER,    // Calls are never recorded - no disclosure needed
    ASK_USER  // Prompt the user for consent before the call connects
}

fun handleRecordingConsent(voice: VoiceCallChannel, onResult: (Boolean) -> Unit) {
    when (voice.recordingOption) {
        RecordingOption.ALWAYS -> {
            showRecordingDisclosure("This call will be recorded.")
            onResult(true)
        }
        RecordingOption.NEVER, null -> onResult(true)
        RecordingOption.ASK_USER -> presentConsentPrompt { granted ->
            onResult(granted)
        }
    }
}

發起即時通話

發起即時通話前:

  1. 檢查所選佇列的 VoiceCallChannel。

  2. 確認已啟用即時通話功能,且通話未轉接。

  3. 根據佇列的recordingOption處理錄音同意聲明。

  4. 要求麥克風權限。

  5. 撥打 startInstantCall

suspend fun initiateInstantCall(queueMenu: QueueMenu) {
    val voice = queueMenu.channels.voiceCall ?: return

    if (!voice.instantEnabled || voice.deflected == true) {
        return
    }

    val recordingPermission = resolveRecordingPermission(voice)
    requestMicrophonePermissionIfNeeded()

    try {
        CCAI.callService?.startInstantCall(
            menuId = queueMenu.id,
            recordingPermission = recordingPermission
        )
    } catch (e: Exception) {
        showCallStartError(e)
    }
}

觀察通話狀態

在發起或接聽通話前,請先收集通話服務事件:

val service = CCAI.callService ?: return

lifecycleScope.launch {
    service.stateChanged.collect { state ->
        updateCallConnectionState(state)
    }
}

lifecycleScope.launch {
    service.callReceived.collect { call ->
        updateCallDetails(call)
    }
}

lifecycleScope.launch {
    service.incomingCallEvent.collect { event ->
        handleIncomingCallEvent(event)
    }
}

lifecycleScope.launch {
    service.waitTimeUpdated.collect { waitTime ->
        updateEstimatedWaitTime(waitTime)
    }
}

lifecycleScope.launch {
    service.participantUpdated.collect { participant ->
        updateParticipantInfo(participant)
    }
}

lifecycleScope.launch {
    service.interruptionDetected.collect { interruption ->
        // A PSTN interruption (for example, an incoming cellular call)
        // has paused the active CCAI call. Surface a "call interrupted"
        // banner and offer a Resume action after the interruption ends.
        showInterruptionBanner(interruption)
    }
}

lifecycleScope.launch {
    service.deflectionOffered.collect { deflection ->
        // The platform offered a wait-time deflection (for example, a
        // scheduled callback or PSTN fallback). Render the prompt and
        // honor the user's choice.
        presentWaitTimeDeflection(deflection)
    }
}

供應商狀態與伺服器狀態

stateChanged 和 callReceived.status 是獨立信號,請將其視為資料欄而非資料列。供應商的 stateChanged 會回報本機 VoIP 握手;伺服器端的 callReceived.status 則會回報平台上的通話生命週期。從callReceived.status開始,而非從stateChanged達到連線狀態,來驅動「已連線」翻轉和通話計時器啟動。

信號 回報內容 可從中取得的資料
stateChanged (供應商) 本地 VoIP 握手信號 - Connecting, Connected (local), Disconnected, Error(...). 伺服器狀態送達前、錯誤浮現時,以及通話結束清理作業期間,可選用的前置狀態微調器。
callReceived.status (伺服器) 伺服器端生命週期 - WAITING、CONNECTING、CONNECTED、ON_HOLD、INTERRUPTED、ENDED。 通話翻轉、通話計時器啟動、指派給專員的 UI、轉接或升級疊加層,以及結束通話流程。

來電

系統會使用 FCM 將來電傳送到裝置。由於來電可能會在應用程式背景執行或完全終止時抵達,因此整合作業必須準備好從任何程序狀態接收來電。

SDK 提供內容:callService 上的 IncomingCallEvent Flow,會發出來電的生命週期:Arrived、Accepted、Rejected。通話服務也會公開 acceptIncomingCall() 和 rejectIncomingCall(),以對提案採取行動。

建構內容:來電 UI (全螢幕鈴聲畫面、鎖定畫面呈現方式或應用程式內橫幅) 和接受或拒絕通話的處理常式。

導入範例

在每個生命週期事件中收集 incomingCallEvent,並顯示或關閉 UI,然後從長期範圍接受或拒絕。在 Application 類別中定義 applicationScope 一次,這樣接受或拒絕協同程式就能在交握期間的任何短暫 Activity 拆除作業中存留。

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withTimeoutOrNull

// Define this in your Application class (or another long-lived singleton).
// Expose it however your app prefers as top-level property, dependency
// injection, or a static field on the Application subclass.
val applicationScope = CoroutineScope(SupervisorJob() + Dispatchers.Main)

lifecycleScope.launch {
    CCAI.callService?.incomingCallEvent?.collect { event ->
        when (event) {
            is IncomingCallEvent.Arrived -> showIncomingCallUi(event.call)
            is IncomingCallEvent.Accepted -> navigateToCallScreen(event.call)
            is IncomingCallEvent.Rejected -> dismissIncomingCallUi()
        }
    }
}

// User taps "Accept" in your custom UI.
fun onAcceptTapped() {
    // Important: accept/reject helpers suspend internally. Launch them on
    // `applicationScope` (defined above) so the call survives if the
    // ringing Activity is dismissed during the handshake.
    applicationScope.launch {
        CCAI.callService?.acceptIncomingCall()
    }
}

fun onRejectTapped() {
    applicationScope.launch {
        CCAI.callService?.rejectIncomingCall()
    }
}

將 FCM 橋接到來電 UI

FCM 傳送的來電會在背景執行緒中送達,通常會在任何 Activity 存在之前送達。使用短暫逾時,將 FCM 酬載橋接至第一次 IncomingCallEvent.Arrived 排放,然後啟動 UI。

導入範例

在下一個 IncomingCallEvent.Arrived 上暫停,並使用 withTimeoutOrNull 交給領航員。

suspend fun handleIncomingCallPush() {
    val arrived = withTimeoutOrNull(60_000L) {
        CCAI.callService?.incomingCallEvent
            ?.filterIsInstance<IncomingCallEvent.Arrived>()
            ?.first()
    } ?: return
    // `myNavigator` is the `IncomingCallUiNavigator` implementation you wire
    // up during app initialization (see "Alternative: full-screen ringing
    // Activity" below). Hold the reference somewhere long-lived (for
    // example, on your `Application` subclass) so it can be reused here.
    myNavigator.showRingingUi(applicationContext, arrived.call.id)
}

如要使用 Android 內建的來電體驗 (全螢幕鈴聲、鎖定螢幕顯示,以及與系統通話記錄整合),請註冊 PhoneAccount,並讓 Telecom 架構擁有鈴聲 UX。

SDK 提供哪些功能:TelecomCallService 輔助程式,可為應用程式 (registerPhoneAccount(context)) 註冊 PhoneAccount、將傳入的 CCAI 呼叫橋接至 Android Telecom 的 TelecomConnectionService,以及用於連線狀態回呼的 TelecomConnectionCallback 介面。

建構內容:應用程式初始化期間的單次 PhoneAccount 註冊,以及連線服務的資訊清單宣告。

導入範例

在應用程式啟動時註冊電話帳戶,然後在資訊清單中宣告連線服務和權限。

// In Application.onCreate(), after CCAI.initializeCall(...)
TelecomCallService.registerPhoneAccount(context = this)
<!-- AndroidManifest.xml -->
<uses-permission android:name="android.permission.MANAGE_OWN_CALLS" />

<service
    android:name="com.ccaiplatform.android.call.TelecomConnectionService"
    android:permission="android.permission.BIND_TELECOM_CONNECTION_SERVICE"
    android:exported="true">
    <intent-filter>
        <action android:name="android.telecom.ConnectionService" />
    </intent-filter>
</service>

替代方案:全螢幕鈴響活動

如果您偏好自行算繪鈴響畫面,而非使用 Telecom 架構,SDK 會公開 IncomingCallService 和 IncomingCallUiNavigator 介面。實作介面,然後在應用程式初始化期間,將實作項目交給 IncomingCallService。

導入範例

實作 IncomingCallUiNavigator,並在 Application.onCreate() 期間將其傳遞至 IncomingCallService 一次。

// 1. Implement the navigator. Override the three interface methods to
//    declare the ringing Activity intent and to show/hide your UI as the
//    call lifecycle changes.
class MyNavigator : IncomingCallUiNavigator {
    override fun ringingActivityIntent(
        context: Context,
        callId: Long,
        callerName: String?
    ): Intent = Intent(context, RingingActivity::class.java).apply {
        putExtra("callId", callId)
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }

    override fun showRingingUi(context: Context, callId: Long) {
        // Optional: surface an in-app banner or push your ringing UI.
    }

    override fun hideRingingUi(context: Context, callId: Long) {
        // Optional: dismiss whatever you surfaced in showRingingUi.
    }
}

// 2. Wire it up during app initialization (typically in Application.onCreate()).
val incomingCallService = IncomingCallService(
    applicationContext,
    MyNavigator()
)
if (!CCAI.canShowIncomingCallFullScreen(context)) {
    CCAI.openFullScreenIntentSettings(context)
}

主動響鈴的前景服務

通話鈴響時,Android 可能會終止背景程序。SDK 會傳送 IncomingRingingService,讓鈴響流程以前景服務的形式保持運作。在資訊清單中宣告,SDK 會在來電時自動啟動和停止。

<service
    android:name="com.ccaiplatform.android.call.IncomingRingingService"
    android:foregroundServiceType="phoneCall"
    android:exported="false" />

<uses-permission android:name="android.permission.FOREGROUND_SERVICE_PHONE_CALL" />

通話狀態和伺服器端狀態

SDK 提供內容:每個 Call 酬載上的伺服器驅動 CallStatus 列舉,說明呼叫在其生命週期中的位置 (例如 CONNECTING、WAITING、CONNECTED、ON_HOLD、INTERRUPTED、ENDED、FAILED)。

您要建構的內容:從 CallStatus 對應到通話畫面上向消費者顯示的狀態。

導入範例

從每個 callReceived 發出作業的 call.status 分支 when,並算繪相符的 UI 狀態:

fun updateCallDetails(call: Call) {
    when (call.status) {
        CallStatus.CONNECTING -> renderConnectingState()
        CallStatus.WAITING -> renderWaitingInQueueState(call.estimatedWait)
        CallStatus.CONNECTED -> renderConnectedState(call.agent)
        CallStatus.ON_HOLD -> renderOnHoldState()
        CallStatus.INTERRUPTED -> renderInterruptedState()
        CallStatus.ENDED, CallStatus.FAILED -> renderEndedState(call.endReason)
    }
}

通話控制項 (靜音、揚聲器、保留)

SDK 提供哪些功能:callService 的唯讀屬性 (isMuted、isSpeakerEnabled、isOnHold),以及切換各狀態的動作 (setMuted、setSpeakerEnabled、setOnHold)。

建構內容:通話中 UI 的靜音、喇叭和保留按鈕,這些按鈕會連結至 SDK 的動作,並反映目前狀態。

導入範例

從 callService 讀取目前狀態,初始化按鈕,然後切換並在輕觸時更新。

muteButton.isSelected = CCAI.callService?.isMuted == true
speakerButton.isSelected = CCAI.callService?.isSpeakerEnabled == true
holdButton.isSelected = CCAI.callService?.isOnHold == true

fun onMuteTapped() {
    val next = CCAI.callService?.isMuted != true
    CCAI.callService?.setMuted(next)
    muteButton.isSelected = next
}

fun onSpeakerTapped() {
    val next = CCAI.callService?.isSpeakerEnabled != true
    CCAI.callService?.setSpeakerEnabled(next)
    speakerButton.isSelected = next
}

fun onHoldTapped() {
    val next = CCAI.callService?.isOnHold != true
    CCAI.callService?.setOnHold(next)
    holdButton.isSelected = next
}

在通話中斷後繼續通話

當 PSTN 中斷 (例如來電) 暫停進行中的 CCAI 通話時,SDK 會保持工作階段運作並發出 interruptionDetected。中斷結束後,應用程式可以繼續通話。

SDK 提供哪些功能:getLastCallInProgress() 查詢進行中的通話 (包括應用程式重新啟動後),以及 resumeCall(call) 將通話帶回前景。

建構內容:UI 中的繼續通話功能提示 (通常是橫幅或中斷結束後自動繼續通話),以及返回通話畫面的導覽功能。

導入範例

使用 getLastCallInProgress 查詢進行中的通話、繼續通話,然後返回通話畫面。

lifecycleScope.launch {
    val call = CCAI.callService?.getLastCallInProgress() ?: return@launch
    try {
        CCAI.callService?.resumeCall(call)
        navigateToCallScreen(call)
    } catch (e: Exception) {
        showCallResumeError(e)
    }
}

從虛擬代理提報

SDK 提供哪些內容:canEscalate(allowSkipVirtualAgent: Boolean) 是 CallResponse (callService.callReceived 發出的模型) 的方法,而不是 callService 本身的方法。系統會根據通話目前的虛擬服務專員狀態,回報目前的通話是否符合轉接給真人服務專員的資格。

建構內容:保留最近的 callReceived 排放量做為「目前通話」,然後將「與真人通話」按鈕的顯示狀態繫結至 currentCall?.canEscalate(...)。allowSkipVirtualAgent 引數是您從呼叫回應本身個別擷取的選單設定值,請勿在正式環境中硬式編碼 true。

導入範例

將最新的 Call 保存在屬性中,然後對其叫用 canEscalate。從選單設定中解決 allowSkipVirtualAgent。

// Held from the most recent `callReceived` emission
private var currentCall: Call? = null

// `allowSkipVirtualAgent` is fetched separately from menu configuration
// it is not derived from the CallResponse.
val allowSkip = menuConfiguration.allowSkipVirtualAgent
val allowed = currentCall?.canEscalate(allowSkipVirtualAgent = allowSkip) == true
talkToAgentButton.isVisible = allowed

語音留言

SDK 提供哪些功能:startVoicemail(VoicemailRequest) callService,以及 VoicemailReason 列舉,說明平台提供語音信箱的原因 (例如下班後備援、容量過大備援或暫時重新導向)。

建構內容:使用者介面中的語音信箱進入點 (通常會在 VoiceCallChannel.voicemailReason 填入內容時顯示,或在通話生命週期解析為語音信箱結果時顯示),以及錄音使用者介面本身。

導入範例

設定 voicemailReason 時,顯示語音信箱按鈕,然後使用 VoicemailRequest 呼叫 startVoicemail。

enum class VoicemailReason {
    AFTER_HOUR_DEFLECTION,
    OVER_CAPACITY_DEFLECTION,
    TEMPORARY_REDIRECTION
}

suspend fun offerVoicemail(menu: QueueMenu) {
    val voice = menu.channels.voiceCall ?: return
    if (voice.voicemailReason == null) return
    try {
        CCAI.callService?.startVoicemail(
            VoicemailRequest(menuId = menu.id)
        )
    } catch (e: Exception) {
        showVoicemailError(e)
    }
}

減少等待時間

如果佇列已開啟,但等待時間超過管理員設定的門檻,平台可以提供替代路徑,通常是預約回撥或 PSTN 轉接。

SDK 提供內容:描述所提供替代方案的 CallDeflection 酬載,可使用 callService 上的 getCallDeflection(callId) 擷取。等待期間發生轉接時,平台也會透過 deflectionOffered Flow 發出相同酬載。另一個 CompanyResponse.preventDirectPstnCall 旗標則表示是否應在備援 UI 中隱藏直接撥打 PSTN 的功能。

建構內容:轉移提示 (例如「預計等待時間為 12 分鐘,要改為安排回撥嗎?」) 和分支邏輯,可根據使用者的選擇採取行動。

導入範例

使用進行中通話的 ID 擷取提供的轉接,將其與 CompanyResponse.preventDirectPstnCall 合併,然後顯示提示。

lifecycleScope.launch {
    val currentCall = CCAI.callService?.getLastCallInProgress()
        ?: return@launch
    val deflection = CCAI.callService?.getCallDeflection(callId = currentCall.id)
        ?: return@launch
    val company = CCAI.companyService?.get()
    val allowDirectPstn = company?.preventDirectPstnCall != true
    presentWaitTimeDeflection(deflection, allowDirectPstn)
}

進階 CallOptions

CallOptions 會公開一小組切換鈕,供需要調整預設通話體驗的應用程式使用。

  • connectingPollIntervalMs:Long - SDK 在呼叫處於連線狀態時輪詢平台的頻率。

  • connectedPollIntervalMs:Long - SDK 在通話連線期間輪詢平台的頻率。

  • endCallMaxRetries:Int - SDK 在顯示錯誤前,重試結束通話要求的次數。

  • endCallRetryDelayMs:Long - 結束通話重試之間的延遲。

導入範例

初始化通話模組時,將調整過的值傳遞至 CallOptions:

CCAI.initializeCall(
    context = this,
    options = CallOptions(
        connectingPollIntervalMs = 2_000L,
        connectedPollIntervalMs = 5_000L,
        endCallMaxRetries = 3,
        endCallRetryDelayMs = 1_000L
    )
)

分享螢幕畫面

支援團隊專員可透過畫面分享功能查看使用者畫面,協助排解問題。CCAI 平台支援兩種螢幕分享模式:

  1. 在應用程式內分享:代理程式只能看到特定應用程式內的畫面。

  2. 完整裝置共用 (選用):代理人可以查看使用者的整個裝置,包括 Android 主畫面和其他應用程式。這需要使用 MediaProjection 和前景服務進行進階 Android 設定。

SDK 提供哪些功能:CCAIScreenShare 模組,可建立及管理工作階段、處理狀態變更,以及處理同意聲明要求。

建構內容:初始化設定、使用者同意聲明的使用者介面提示,以及 (如果支援完整裝置) 內建 Android MediaProjection 與前景服務的整合。

螢幕分享服務提供完整工作階段生命週期的方法 (startSession、activateSession、stopSession),以及遠端控制和分享完整裝置的設定方法。接下來的子章節將逐步說明核心整合流程。

如要查看所有螢幕分享方法的完整方法簽章和參數詳細資料,請參閱「Headless Mobile SDK - Android API 參考資料」。

初始化及設定螢幕分享功能

在應用程式設定期間,提供螢幕分享金鑰,初始化螢幕分享服務:

import com.ccaiplatform.android.CCAI
import com.ccaiplatform.android.ScreenShareOptions

// Minimal - domain defaults to your instance's configured provider
CCAI.initializeScreenShare(
    context = this,
    screenShareOptions = ScreenShareOptions(
        key = "YOUR_SCREEN_SHARE_KEY"
    )
)

// If your instance or provider requires an explicit domain:
// CCAI.initializeScreenShare(
//     context = this,
//     screenShareOptions = ScreenShareOptions(
//         key = "YOUR_SCREEN_SHARE_KEY",
//         domain = "your_subdomain.ccaiplatform.com"
//     )
// )

確認螢幕分享資格

啟用分享螢幕畫面功能前,請先確認目前對話是否支援這項功能:

import com.ccaiplatform.ccaiscreenshare.ScreenShareManager

fun isScreenShareEnabled(chat: ChatResponse): Boolean {
    return CCAI.screenShareService != null
        && chat.supportScreenShare == true
}

處理螢幕畫面分享要求

使用 ScreenShareManager 實作螢幕分享要求處理程序。您可以使用 ScreenShareCallbacks 建立工作階段並處理非同步回應:

import com.ccaiplatform.ccaiscreenshare.ScreenShareManager
import com.ccaiplatform.ccaiscreenshare.ScreenShareCallbacks

fun requestScreenShare(chatId: String, isFromRemote: Boolean) {
    val screenShareService = CCAI.screenShareService
    if (screenShareService == null) {
        Log.e("ScreenShare", "Screen share service not available")
        return
    }

    // Track whether this session is agent-initiated
    screenShareInitiatedFrom = if (isFromRemote) "agent" else "endUser"

    if (!isFromRemote) {
        sendScreenShareMessage(event = "screenShareRequestedFromEndUser")
    }

    val callbacks = ScreenShareCallbacks(
        onSessionStateChanged = { state ->
            Log.d("ScreenShare", "State changed: $state")
            handleScreenShareStateChange(state)
        },
        onSessionCreationError = { error ->
            Log.e("ScreenShare", "Session creation failed: ${error.message}")
            sendScreenShareMessage(event = "screenShareFailed")
            showErrorToast("Screen share failed to start.")
        },
        onSessionActivationRequest = {
            Log.d("ScreenShare", "Activation request received")
            // For agent-initiated sessions, activate immediately
            // For user-initiated sessions, show a confirmation dialog first
            if (screenShareInitiatedFrom == "agent") {
                ScreenShareManager.activateSession()
            } else {
                showScreenShareConsentDialog {
                    ScreenShareManager.activateSession()
                }
            }
        }
    )

    ScreenShareManager.startSession(
        request = ScreenShareRequest(
            communicationId = chatId,
            communicationType = CommunicationType.Chat,
            initiatedFrom = if (isFromRemote) ScreenShareFrom.AGENT else ScreenShareFrom.END_USER
        ),
        callbacks = callbacks
    )
}

處理螢幕畫面分享狀態變更

透過提供給 ScreenShareCallbacks 的 onSessionStateChanged 回呼,監聽螢幕分享工作階段狀態變更:

fun handleScreenShareStateChange(state: ScreenShareSessionState) {
    currentScreenShareSessionState = state

    when (state) {
        ScreenShareSessionState.INACTIVE -> {
            Log.d("ScreenShare", "No active session")
        }
        ScreenShareSessionState.PENDING -> {
            Log.d("ScreenShare", "Session pending - waiting for activation")
            // For agent-initiated sessions, activate immediately
            if (screenShareInitiatedFrom == "agent") {
                ScreenShareManager.activateSession()
            }
        }
        ScreenShareSessionState.ACTIVE -> {
            Log.d("ScreenShare", "Screen share active")
            sendScreenShareMessage(event = "screenShareStarted")
            updateUiForActiveScreenShare()
        }
    }
}

ScreenShareCallbacks 參考資料

回撥電話 說明
onSessionStateChanged 當螢幕分享工作階段狀態變更時 (INACTIVE、PENDING、ACTIVE),系統會呼叫這個方法。
onSessionCreationError 工作階段建立失敗時呼叫的方法 (網路問題、服務無法使用等)。
onSessionActivationRequest 工作階段準備好啟用時呼叫,請呼叫 ScreenShareManager.activateSession() 開始分享。如果是使用者發起的工作階段,請先顯示同意提示;如果是代理程式發起的工作階段,請立即啟動。
onSessionRemoteControlRequest 當代理要求遠端控制使用者的螢幕時,系統會呼叫這個方法。先顯示同意提示,再授予遠端控制權。
onSessionFullDeviceRequest 當服務專員要求分享整個裝置的畫面時 (請參閱下方的「分享整個裝置的畫面」),系統會呼叫這個方法。在回應中觸發 MediaProjection 同意聲明流程。
onSessionDidSucceed 工作階段成功啟用並開始串流後,系統會呼叫此方法。使用這個狀態將 UI 更新為「畫面分享已啟用」狀態。

如需完整的狀態列舉定義和所有相關聯的型別,請參閱「無頭行動 SDK - Android API 參考資料」。

分享整個裝置畫面 (進階)

分享整個裝置的畫面後,服務專員就能查看您裝置上其他應用程式的畫面,包括系統設定和應用程式間的導覽畫面。這需要整合 Android 的 MediaProjection API,並執行前景服務。

宣告權限和前景服務

在下列位置新增必要權限和前景服務聲明:AndroidManifest.xml

<manifest>
    <!-- Required for screen capture -->
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />

    <application>
        <service
            android:name=".screenshare.ScreenShareForegroundService"
            android:foregroundServiceType="mediaProjection"
            android:exported="false" />
    </application>
</manifest>

擷取畫面之前,請務必使用 MediaProjectionManager 提示使用者同意:

import android.media.projection.MediaProjectionManager
import android.content.Context

private val mediaProjectionManager by lazy {
    getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
}

fun requestScreenCapturePermission() {
    val captureIntent = mediaProjectionManager.createScreenCaptureIntent()
    screenCaptureResultLauncher.launch(captureIntent)
}

// Handle the result in your Activity
private val screenCaptureResultLauncher = registerForActivityResult(
    ActivityResultContracts.StartActivityForResult()
) { result ->
    if (result.resultCode == Activity.RESULT_OK && result.data != null) {
        // User granted screen capture permission
        startScreenShareForegroundService(result.resultCode, result.data!!)
    } else {
        Log.d("ScreenShare", "User denied screen capture permission")
    }
}

實作前景服務

建立前景服務,保存 MediaProjection 工作階段:

import android.app.Service
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Intent
import android.os.IBinder

class ScreenShareForegroundService : Service() {

    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        val notification = buildNotification()
        startForeground(NOTIFICATION_ID, notification)
        return START_NOT_STICKY
    }

    override fun onBind(intent: Intent?): IBinder? = null

    private fun createNotificationChannel() {
        val channel = NotificationChannel(
            CHANNEL_ID,
            "Screen Share",
            NotificationManager.IMPORTANCE_LOW
        ).apply {
            description = "Active screen share session"
        }
        val manager = getSystemService(NotificationManager::class.java)
        manager.createNotificationChannel(channel)
    }

    private fun buildNotification(): Notification {
        return Notification.Builder(this, CHANNEL_ID)
            .setContentTitle("Screen Sharing")
            .setContentText("An agent is viewing your screen.")
            .setSmallIcon(R.drawable.ic_screen_share)
            .build()
    }

    companion object {
        private const val CHANNEL_ID = "screen_share_channel"
        private const val NOTIFICATION_ID = 1001
    }
}

啟用完整裝置共用功能

MediaProjection啟用後,請透過螢幕分享服務啟用全裝置分享功能:

// After MediaProjection consent is granted and foreground service is started
ScreenShareManager.enableFullDeviceSharing(true)

螢幕分享的 Jetpack Compose 注意事項

  1. 使用 Android 檢視區塊包裝主要互動式元素:如要讓區域可遠端點選,請使用 AndroidView 可組合函式,將這些區域包裝為標準 Android 檢視區塊控制項 (例如 android.widget.Button)。這樣可確保透過 Android 檢視區塊路徑,遠端點擊功能能穩定運作。

  2. 透過自訂觸控處理方式轉送遠端觸控事件:對於無法以 Views 取代的 Compose 區域,請使用自訂觸控回呼,將遠端觸控事件轉送至 Compose 邏輯。

  3. 提供產品層級的指引或備援:在撰寫畫面中清楚指出「代理人只能查看,使用者必須輕觸本機」,或自動限制這些頁面的遠端控制權限,同時維持僅供查看的存取權。

Android 檢視區塊包裝函式導入範例

import androidx.compose.runtime.Composable
import androidx.compose.ui.viewinterop.AndroidView
import android.widget.Button

@Composable
fun RemoteControlButton(
    title: String,
    onClick: () -> Unit
) {
    AndroidView(
        factory = { context ->
            Button(context).apply {
                text = title
                setOnClickListener { onClick() }
            }
        },
        update = { button ->
            button.text = title
        }
    )
}

// Usage in a Composable
@Composable
fun ScreenShareSupportScreen() {
    Column {
        Text("This screen supports remote control")
        RemoteControlButton(title = "Clickable Button") {
            println("Button tapped remotely or locally")
        }
    }
}

排定通話

使用者可以預約未來的語音通話,不必排隊等待即時通話。在 Android 上,SDK 會公開呼叫服務方法,用於檢查空檔、擷取時段、預約通話、重新安排通話時間、取消通話,以及處理排程錯誤。

功能偵測

SDK 提供內容:VoiceCallChannel 上的 scheduleEnabled 標記,可指出所選佇列是否支援預約日後通話。

建構內容:在顯示預約進入點前,檢查這個旗標的邏輯。

導入範例

檢查佇列語音通話頻道中的 scheduleEnabled。請勿使用 voiceCall != null 做為 Proxy,因為佇列可以支援即時語音通話,但無法支援排定時間的通話,反之亦然。

fun setupScheduledCallEntryPoint(queueMenu: QueueMenu) {
    val voiceChannel = queueMenu.channels.voiceCall

    if (voiceChannel == null) {
        callNowButton.isVisible = false
        scheduleCallButton.isVisible = false
        return
    }

    callNowButton.isVisible = voiceChannel.instantEnabled && voiceChannel.deflected != true
    scheduleCallButton.isVisible = voiceChannel.scheduleEnabled == true
}

選用可用性檢查

顯示時段選擇器前,你可以先檢查所選佇列是否有可預約的時段。

導入範例

請使用 hasScheduledTimeSlots(menuId:) 做為輕量型預先檢查。如果傳回 false,請顯示空白狀態或備用選項,而非開啟挑選器。

lifecycleScope.launch {
    try {
        val available = CCAI.callService?.hasScheduledTimeSlots(menuId = menu.id) == true
        if (available) {
            showScheduleCallUI()
        } else {
            showNoSlotsMessage()
        }
    } catch (e: Exception) {
        Log.e("CCAI", "Availability check failed: ${e.message}")
        showNoSlotsMessage()
    }
}

擷取時段

擷取所選佇列可預約的時間。SDK 會傳回日期值,應用程式可以採用使用者的當地時區顯示這些值。

SDK 提供哪些功能:所選佇列的可用時段時間戳記,並可選擇支援重新安排現有預約通話。

您要建構的內容:日曆、時間挑選器、時區呈現方式、空白狀態處理和重試行為。

導入範例

使用佇列選單 ID 呼叫 getScheduledTimeSlots。 重新安排時間時,請傳遞現有的預約通話 ID,服務才能傳回適當的空檔。

lifecycleScope.launch {
    try {
        val slots: List<Date> = CCAI.callService?.getScheduledTimeSlots(
            menuId = menu.id,
            callIdForRescheduling = null
        ) ?: emptyList()

        if (slots.isEmpty()) {
            showNoSlotsMessage()
        } else {
            displayTimeSlotPicker(slots)
        }
    } catch (e: Exception) {
        Log.e("CCAI", "Failed to fetch time slots: ${e.message}")
    }
}

重新安排時間時,請傳遞現有的預約通話 ID:

val slots = CCAI.callService?.getScheduledTimeSlots(
    menuId = menu.id,
    callIdForRescheduling = existingCallId
) ?: emptyList()

建立預定通話

使用者選取時段後,請透過 callService 建立預約通話。

SDK 提供哪些功能:createScheduledCall API,可預訂所選時段並傳回排定通話的記錄。

您要建構的內容:E.164 電話號碼驗證、確認 UI、排定通話 ID 的本機持續性,以及時段衝突或下班後回覆的復原機制。

導入範例

在 ScheduledCallRequest 中傳遞所選時段、電話號碼、佇列 ID 和 RecordingPermission.NOT_ASKED。

lifecycleScope.launch {
    try {
        val response = CCAI.callService?.createScheduledCall(
            ScheduledCallRequest(
                menuId = menu.id,
                phoneNumber = userPhoneNumber,
                scheduleTime = selectedSlot,
                recordingPermission = RecordingPermission.NOT_ASKED,
                callIdForRescheduling = null,
                customData = null,
                ticketId = null
            )
        )

        saveScheduledCallId(response?.id)
        showConfirmation(scheduledAt = response?.scheduledAt)
    } catch (e: CallCreationError.AfterHours) {
        showMessage(e.displayMessage)
        refreshTimeSlots()
    } catch (e: Exception) {
        Log.e("CCAI", "Failed to schedule call: ${e.message}")
    }
}

電話號碼必須採用 E.164 格式,例如 +14155551234。

重新安排現有通話時間

如要重新安排時間,請擷取時段,並使用現有的 scheduled-call ID 建立新的預約通話。

SDK 提供哪些功能:相同的時段和建立 API,並使用 callIdForRescheduling 識別現有預訂。

建構內容:「變更時間」使用者介面、儲存的預約通話 ID 本機查詢,以及建立新預約後更新的確認狀態。

導入範例

將現有通話 ID 傳遞至 getScheduledTimeSlots 和 createScheduledCall。

lifecycleScope.launch {
    try {
        val slots = CCAI.callService?.getScheduledTimeSlots(
            menuId = menu.id,
            callIdForRescheduling = existingCallId
        ) ?: emptyList()

        val response = CCAI.callService?.createScheduledCall(
            ScheduledCallRequest(
                menuId = menu.id,
                phoneNumber = userPhoneNumber,
                scheduleTime = newSelectedSlot,
                recordingPermission = RecordingPermission.NOT_ASKED,
                callIdForRescheduling = existingCallId,
                customData = null,
                ticketId = null
            )
        )

        saveScheduledCallId(response?.id)
        showConfirmation(scheduledAt = response?.scheduledAt)
    } catch (e: CallCreationError.AfterHours) {
        showMessage(e.displayMessage)
        refreshTimeSlots()
    } catch (e: Exception) {
        Log.e("CCAI", "Failed to reschedule: ${e.message}")
    }
}

取消預定通話

使用者取消預約通話時,請呼叫 cancelScheduledCall 並清除本機儲存的通話 ID。

SDK 提供哪些功能:取消排定通話 ID 的 API。

建構內容:確認提示、取消成功或錯誤 UI,以及清除任何本機儲存的即將來電狀態。

導入範例

使用儲存的 ID 呼叫 cancelScheduledCall(callId:),然後從應用程式的儲存空間中移除 ID。

lifecycleScope.launch {
    try {
        CCAI.callService?.cancelScheduledCall(callId = existingCallId)
        clearScheduledCallId()
        showCancellationConfirmation()
    } catch (e: Exception) {
        Log.e("CCAI", "Failed to cancel call: ${e.message}")
    }
}

電子郵件

SDK 提供的資訊:為特定佇列設定的目的地電子郵件地址,以及管理員希望使用者看到的任何指示 (例如請附上帳號)。

建構內容:電子郵件撰寫畫面和追蹤完成情況的邏輯。您可以自行建構自訂表單,也可以使用 Android 內建的 Intent.ACTION_SENDTO 啟動使用者偏好的電子郵件用戶端。

導入範例

這段程式碼會從 QueueMenu 的 SDK Channels 物件中,提取支援電子郵件地址。這會開啟內建的 Android 電子郵件用戶端,並處理未安裝電子郵件用戶端的案例。

import android.content.Intent
import android.net.Uri
import android.widget.Toast

class SupportActivity : AppCompatActivity() {

    // 1. Trigger the email flow
    fun openEmailComposer(queueMenu: QueueMenu) {
        val emailChannel = queueMenu.channels.email ?: return
        val emailAddress = emailChannel.email ?: return

        val emailIntent = Intent(Intent.ACTION_SENDTO).apply {
            data = Uri.parse("mailto:")
            putExtra(Intent.EXTRA_EMAIL, arrayOf(emailAddress))
            putExtra(Intent.EXTRA_SUBJECT, "Support Request: ${queueMenu.name ?: ""}")
            // If the queue provides an instruction message, include it in the body
            // putExtra(Intent.EXTRA_TEXT, emailChannel.instructionMessage ?: "")
        }

        if (emailIntent.resolveActivity(packageManager) != null) {
            emailResultLauncher.launch(emailIntent)
        } else {
            Toast.makeText(
                this,
                "No email client installed on this device.",
                Toast.LENGTH_LONG
            ).show()
        }
    }

    // 2. Track the outcome using ActivityResultContract
    private val emailResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartActivityForResult()
    ) { result ->
        // Note: Most Android email clients don't return a meaningful
        // result code. Unlike iOS's MFMailComposeViewControllerDelegate,
        // Android's email intent doesn't reliably report whether the
        // email was sent, saved as draft, or cancelled.
        // Log this event to your analytics and assume the user
        // interacted with the email composer.
        Log.d("CCAI", "Email composer closed. Result code: ${result.resultCode}")
        MyAnalytics.logEvent("email_composer_closed")
    }
}

SDK 提供的內容:網址清單 (例如貴公司的說明中心、退款政策或合作夥伴應用程式) 及其顯示標題,與管理入口網站中的設定完全一致。

建構內容:使用者輕觸連結時執行這些連結的邏輯,方法是在應用程式內瀏覽器中開啟連結 (使用 Android 的自訂分頁),或是啟動預設系統瀏覽器。

使用者輕觸選單中的外部連結時,這段程式碼會擷取 SDK 提供的網址字串,並使用 Chrome 自訂分頁在應用程式內瀏覽器中顯示網頁。與啟動完整瀏覽器應用程式相比,自訂分頁提供更快速流暢的體驗,同時仍會顯示網址列,讓使用者知道自己正在查看外部內容。

import androidx.browser.customtabs.CustomTabsIntent
import android.net.Uri

fun openHelpCenterLink(urlString: String) {
    val uri = Uri.parse(urlString) ?: return

    val customTabsIntent = CustomTabsIntent.Builder()
        .setShowTitle(true)
        .build()

    customTabsIntent.launchUrl(this, uri)
}

備援實作 (系統瀏覽器):如果無法使用自訂分頁,或您偏好較簡單的方法,可以在使用者的預設瀏覽器中開啟連結:

import android.content.Intent
import android.net.Uri

fun openHelpCenterLink(urlString: String) {
    val uri = Uri.parse(urlString) ?: return

    val intent = Intent(Intent.ACTION_VIEW, uri)
    if (intent.resolveActivity(packageManager) != null) {
        startActivity(intent)
    } else {
        showErrorToast("No browser available to open this link.")
    }
}

完整整合範例

這段程式碼會從 SDK 的 Channels 物件讀取轉向連結,並在頻道選單中以可輕觸的按鈕形式呈現給使用者。

fun setupDeflectionLinks(queueMenu: QueueMenu) {
    val deflectionLink = queueMenu.channels.externalDeflectionLink

    if (deflectionLink != null) {
        helpCenterButton.isVisible = true
        helpCenterButton.setOnClickListener {
            // Read the URL from the structured ExternalDeflectionLink type
            val url = deflectionLink.url ?: return@setOnClickListener
            openHelpCenterLink(url)
        }
    } else {
        helpCenterButton.isVisible = false
    }
}

ExternalDeflectionLink 會公開頂層 url / displayName 欄位和內部 links: List<ExternalDeflection>? 陣列。上述範例只會算繪頂層項目,這對單一連結佇列來說已足夠。如果管理員在單一佇列中設定多個外部連結,請疊代 deflectionLink.links 並為每個已啟用項目算繪一個按鈕,每個按鈕都會攜帶自己的 url 和 displayName:ExternalDeflection

deflectionLink.links
    ?.filter { it.enabled == true }
    ?.forEach { link ->
        val button = MaterialButton(this).apply {
            text = link.displayName
            setOnClickListener { openHelpCenterLink(link.url) }
        }
        helpCenterContainer.addView(button)
    }