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

# Android

> Integrate Humain Kiosk into an Android app — text chat, streaming, and real-time voice with Jetpack Compose.

The Android SDK provides coroutine-native APIs and Kotlin `Flow` for text streaming, and a
full WebRTC voice pipeline with `AudioManager` integration. The underlying WebRTC protocol is
described in the [WebRTC connection guide](https://humain.mintlify.site/connections/webrtc-voice.md) — this page covers the
Android-specific implementation.

> [!TIP]
>
> During development, initialise the client with an `hk_test_…` sandbox credential instead of
> `hk_live_…`. There is no separate sandbox mode or URL — sandbox behavior comes entirely from
> the credential prefix. No AI credits are consumed and no usage is billed. See
> [Sandbox mode](https://humain.mintlify.site/concepts/sandbox-mode.md).

***

## Install

Add the dependency to your `build.gradle.kts`:

```kotlin theme={null}
dependencies {
    implementation("ai.humain:kiosk-android:1.0.0")
}
```

Add permissions to `AndroidManifest.xml`:

```xml theme={null}
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
```

> [!WARNING]
>
> `RECORD_AUDIO` is a dangerous permission — it must be requested at runtime before starting
> a voice session. The SDK throws `MicrophonePermissionException` if the permission is absent.
> See the [Requesting microphone permission at runtime](#requesting-microphone-permission-at-runtime)
> accordion below.

***

## Text and streaming

> [tab] Text session
>
> Open a session, send a message, and close in a `try/finally` block to ensure cleanup.
>
> ```kotlin theme={null}
> class ChatViewModel : ViewModel() {
>     private val kiosk = KioskClient(
>         KioskConfig(credential = BuildConfig.HUMAIN_CREDENTIAL)
>     )
>
>     private val _response = MutableStateFlow("")
>     val response: StateFlow<String> = _response.asStateFlow()
>
>     private val _isLoading = MutableStateFlow(false)
>     val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()
>
>     fun sendMessage(text: String) {
>         viewModelScope.launch {
>             _isLoading.value = true
>             val session = kiosk.openSession()
>             try {
>                 val result = session.sendMessage(text)
>                 _response.value = result.text
>             } catch (e: KioskException) {
>                 _response.value = "Error: ${e.message}"
>             } finally {
>                 session.close()
>                 _isLoading.value = false
>             }
>         }
>     }
> }
> ```

> [tab] Streaming
>
> `session.stream()` returns a cold `Flow<StreamEvent>`. Collect it inside a coroutine.
>
> ```kotlin theme={null}
> class ChatViewModel : ViewModel() {
>     private val kiosk = KioskClient(
>         KioskConfig(credential = BuildConfig.HUMAIN_CREDENTIAL)
>     )
>
>     private val _streamedText = MutableStateFlow("")
>     val streamedText: StateFlow<String> = _streamedText.asStateFlow()
>
>     fun streamMessage(text: String) {
>         viewModelScope.launch {
>             val session = kiosk.openSession()
>             try {
>                 val accumulated = StringBuilder()
>                 session.stream(text).collect { event ->
>                     if (event is StreamEvent.Chunk) {
>                         accumulated.append(event.content)
>                         _streamedText.value = accumulated.toString()
>                     }
>                 }
>             } catch (e: KioskException) {
>                 _streamedText.value = "Error: ${e.message}"
>             } finally {
>                 session.close()
>             }
>         }
>     }
> }
> ```
>
> Stream event types:
>
> | Type | Properties | Description |
> | - | - | - |
> | `StreamEvent.TurnStart` | — | AI has started generating |
> | `StreamEvent.Chunk` | `content: String` | Append to output buffer |
> | `StreamEvent.ToolCall` | `name`, `callId` | Action endpoint invoked |
> | `StreamEvent.ToolResult` | `callId`, `status` | Action returned |
> | `StreamEvent.TurnEnd` | `messageCount: Int` | Generation complete |

***

## Voice session

```kotlin theme={null}
class VoiceViewModel : ViewModel() {
    private val kiosk = KioskClient(
        KioskConfig(credential = BuildConfig.HUMAIN_CREDENTIAL)
    )
    private var voiceSession: VoiceSession? = null

    val status = MutableStateFlow(VoiceStatus.IDLE)
    val transcript = MutableStateFlow("")
    val lastResponse = MutableStateFlow("")

    fun startSession(context: Context) {
        viewModelScope.launch {
            // Configure AudioManager for in-call audio
            val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            audioManager.mode = AudioManager.MODE_IN_COMMUNICATION
            audioManager.isSpeakerphoneOn = true

            try {
                voiceSession = kiosk.openVoiceSession(
                    listener = object : VoiceSessionListener {
                        override fun onTranscript(text: String) {
                            transcript.value = text
                        }
                        override fun onResponse(text: String) {
                            lastResponse.value = text
                        }
                        override fun onStatusChange(s: VoiceStatus) {
                            status.value = s
                        }
                        override fun onError(e: KioskException) {
                            // Handle error — reset state
                            status.value = VoiceStatus.IDLE
                        }
                    }
                )
                voiceSession?.start()
            } catch (e: KioskException.MicrophonePermissionException) {
                // RECORD_AUDIO not granted — prompt in UI layer, not here
            }
        }
    }

    fun stopSession(context: Context) {
        viewModelScope.launch {
            voiceSession?.stop()
            voiceSession = null
            val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
            audioManager.mode = AudioManager.MODE_NORMAL
            audioManager.isSpeakerphoneOn = false
            status.value = VoiceStatus.IDLE
        }
    }
}
```

***

### Requesting microphone permission at runtime

> [accordion] Requesting microphone permission at runtime
>
> Use the Compose `rememberLauncherForActivityResult` pattern to request `RECORD_AUDIO`
> before starting a voice session:
>
> ```kotlin theme={null}
> @Composable
> fun VoiceScreen(viewModel: VoiceViewModel = viewModel()) {
>     val context = LocalContext.current
>     val status by viewModel.status.collectAsState()
>
>     val micPermissionLauncher = rememberLauncherForActivityResult(
>         ActivityResultContracts.RequestPermission()
>     ) { granted ->
>         if (granted) {
>             // Permission granted — safe to start
>             viewModel.startSession(context)
>         } else {
>             // Permission denied — show rationale
>         }
>     }
>
>     Button(
>         onClick = {
>             when {
>                 ContextCompat.checkSelfPermission(
>                     context, Manifest.permission.RECORD_AUDIO
>                 ) == PackageManager.PERMISSION_GRANTED -> {
>                     viewModel.startSession(context)
>                 }
>                 else -> micPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
>             }
>         }
>     ) {
>         Text(if (status == VoiceStatus.IDLE) "Start conversation" else "Listening…")
>     }
> }
> ```

### Handling audio focus

> [accordion] Requesting and abandoning audio focus
>
> Request audio focus before starting the voice session so your app ducks music apps and
> receives focus-change events (e.g., when a call arrives):
>
> ```kotlin theme={null}
> private var audioFocusRequest: AudioFocusRequest? = null
>
> private fun requestAudioFocus(context: Context): Boolean {
>     val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
>     val focusChangeListener = AudioManager.OnAudioFocusChangeListener { focusChange ->
>         when (focusChange) {
>             AudioManager.AUDIOFOCUS_LOSS,
>             AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
>                 // Phone call or other app took focus — mute our session
>                 voiceSession?.isMuted = true
>             }
>             AudioManager.AUDIOFOCUS_GAIN -> {
>                 // Focus returned — unmute
>                 voiceSession?.isMuted = false
>             }
>         }
>     }
>
>     val request = AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
>         .setAudioAttributes(
>             AudioAttributes.Builder()
>                 .setUsage(AudioAttributes.USAGE_VOICE_COMMUNICATION)
>                 .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
>                 .build()
>         )
>         .setOnAudioFocusChangeListener(focusChangeListener)
>         .build()
>
>     audioFocusRequest = request
>     return audioManager.requestAudioFocus(request) == AudioManager.AUDIOFOCUS_REQUEST_GRANTED
> }
>
> private fun abandonAudioFocus(context: Context) {
>     val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
>     audioFocusRequest?.let { audioManager.abandonAudioFocusRequest(it) }
>     audioFocusRequest = null
> }
> ```
>
> Call `requestAudioFocus()` before `voiceSession.start()` and `abandonAudioFocus()` after
> `voiceSession.stop()`.

### Bluetooth headset support

> [accordion] Enabling Bluetooth SCO for hands-free audio
>
> To route audio through a paired Bluetooth headset, enable Bluetooth SCO before starting
> the voice session:
>
> ```kotlin theme={null}
> private fun enableBluetoothSco(context: Context) {
>     val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
>     if (audioManager.isBluetoothScoAvailableOffCall) {
>         audioManager.startBluetoothSco()
>         audioManager.isBluetoothScoOn = true
>     }
> }
>
> private fun disableBluetoothSco(context: Context) {
>     val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
>     audioManager.stopBluetoothSco()
>     audioManager.isBluetoothScoOn = false
> }
> ```
>
> Add the additional manifest permission:
>
> ```xml theme={null}
> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
> ```
>
> And call `enableBluetoothSco(context)` after `audioManager.mode = AudioManager.MODE_IN_COMMUNICATION`,
> before `voiceSession.start()`.

***

> [!WARNING]
>
> Never hard-code your credential. Read it from an environment variable:

```python Python theme={null}
import os
from humain_kiosk import KioskClient

client = KioskClient(credential=os.environ["HUMAIN_CREDENTIAL"])
```

```go Go theme={null}
import (
    "os"
    kiosk "github.com/humain/kiosk-go"
)

client := kiosk.New(kiosk.Config{
    Credential: os.Getenv("HUMAIN_CREDENTIAL"),
})
```

```csharp .NET theme={null}
// appsettings.json: { "Humain": { "Credential": "hk_live_..." } }
var client = new KioskClient(new KioskClientOptions
{
    Credential = configuration["Humain:Credential"],
});
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.