Multiplatform Android crashes on launch of coroutine

I am working on my first multiplatform app. All my code is in the App.kt (kotlin commonMain) file. The desktop app runs and works perfectly. But the Android app (API 34) launches and immediately crashes. I have identified that it crashes when I attempt to launch a coroutine (i.e. by commenting out the scope.launch block, the app does not crash). I have tried more things that I can iterate here, but nothing seems to change the symptom. What am I doing wrong that would prevent the same code from running successfully on Android?

@Composable
fun App() {
    MaterialTheme {
        var statusMessage by remember { mutableStateOf("") }
        var expiration by remember { mutableStateOf("0") }
        val client = HttpClient(CIO)
        val scope = CoroutineScope(Dispatchers.IO)

        scope.launch {
            while(true) {
                val onResponse = client.get("http://192.168.1.79:5000/state")
                statusMessage = onResponse.bodyAsText()
                println(statusMessage)
                delay(5000)
            }
        }
        ...

build.gradle.kts:

  • The commonMain.dependencies contains: implementation(“org.jetbrains.kotlinx:kotlinx-coroutines-core:1.8.1”)
  • And the Android dependencies contains: implementation(“org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1”)

Thanks in advance!

Do you have a stack trace or an error message?

I didn’t really, other than a lot of Matlog data. However, your question motivated me to see if I could wrap the most likely culprit in try/catch and dump the exception message to the screen. This gave me a weird “operation not permitted” message. I “googled” this and quickly felt like an idiot. I was missing the following from the manifest:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
1 Like