Kotlin
ChatClient
Before you can start a chat, the Client SDK needs to authenticate to the Vonage servers. Start by creating a new Kotlin file ChatViewModel.kt.
Create a new class ChatViewModel:
class ChatViewModel(application: Application) : AndroidViewModel(application = application) {
private val aliceJwt = "ALICE_JWT"
private val bobJwt = "BOB_JWT"
var isLoggedIn by mutableStateOf(false)
var isError by mutableStateOf(false)
var error = ""
var events : SnapshotStateList<PersistentConversationEvent> = mutableStateListOf()
private var client = ChatClient(getApplication<Application>().applicationContext)
fun login(username: String) {
val jwt = if(username == "Alice") aliceJwt else bobJwt
client.createSession(jwt) { err, sessionId ->
when {
err != null -> {
isError = true
error = err.localizedMessage?.toString() ?: ""
}
else -> {
isLoggedIn = true
}
}
}
}
}
This class will create an instance of ChatClient then create a session using a JWT. Replace ALICE_JWT and BOB_JWT with the JWTs you created earlier.
Button Actions
For the log in buttons to work, you need to add actions to them which will run a function when they are tapped. Update the view code in MainActivity.kt to instantiate a ChatViewModel object and call its login function:
class MainActivity : ComponentActivity() {
private val chatState by viewModels<ChatViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CompositionLocalProvider(LocalChatState provides chatState) {
LoginScreen()
}
}
}
}
val LocalChatState = compositionLocalOf<ChatViewModel> { error("Login State Context Not Found!") }
@Composable
fun LoginScreen() {
val vm = LocalChatState.current
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Button(onClick = { vm.login("Alice") }) {
Text("Login as Alice")
}
Button(onClick = { vm.login("Bob") }) {
Text("Login as Bob")
}
}
}
Creating an Android chat app
Create a Android application that enables users to message each other using the Android Client SDK and Kotlin.
手順
1
Introduction to this task2
Prerequisites3
Create a Vonage Application4
Create a conversation5
Create the users6
Generate JWTs7
Create an Android project8
Building the log in interface9
ChatClient10
Building the chat interface11
Chat events12
Sending a message13
What's next?