How to run the main function in KMP? #69
Answered
by
davidepianca98
prestondavid99
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
davidepianca98
Dec 11, 2024
Replies: 1 comment 1 reply
-
Hello, you cannot run an arbitrary main function in Android, but you have to follow the Activity Lifecycle. This is one simple example I set up, this is a super basic and useless example but it gives a starting point. fun runClient() {
CoroutineScope(Dispatchers.IO).launch {
val client = MQTTClient(
MQTTVersion.MQTT5,
"test.mosquitto.org",
8081,
TLSClientSettings(serverCertificate = MOSQUITTO_CA_WS),
keepAlive = 30,
webSocket = "/mqtt"
) {
println(it.payload?.toByteArray()?.decodeToString())
}
client.subscribe(
listOf(
Subscription(
"test_sub",
SubscriptionOptions(Qos.AT_LEAST_ONCE)
)
)
)
launch {
while (true) {
delay(1000)
client.publish(
false,
Qos.AT_MOST_ONCE,
"test_publish",
"hello1".toByteArray().toUByteArray()
)
}
}
while (client.isRunning()) {
client.step()
delay(100)
}
}
}
class MainActivity : ComponentActivity() {
private fun getTlsFilepath(): String {
val inputStream = application.resources.openRawResource(R.raw.keystore)
val file = File.createTempFile("keystore", ".p12", application.cacheDir)
val outputStream = FileOutputStream(file)
inputStream.use { input ->
outputStream.use { output ->
input.copyTo(output)
}
}
return file.absolutePath
}
@ExperimentalUnsignedTypes
fun runBroker() {
CoroutineScope(Dispatchers.IO).launch {
val broker = Broker(
port = 8883,
tlsSettings = TLSSettings(
keyStoreFilePath = getTlsFilepath(),
keyStorePassword = "changeit"
),
authentication = null
)
broker.listen()
}
}
@OptIn(ExperimentalUnsignedTypes::class)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TestKmqttTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Greeting("Android")
}
}
}
runClient()// or runBroker()
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
TestKmqttTheme {
Greeting("Android")
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
prestondavid99
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello, you cannot run an arbitrary main function in Android, but you have to follow the Activity Lifecycle. This is one simple example I set up, this is a super basic and useless example but it gives a starting point.