Amazon IVS Chat Client Messaging SDK: Android Guide
The Amazon Interactive Video (IVS) Chat Client Messaging Android SDK provides interfaces that allow you to easily incorporate our IVS Chat Messaging API on platforms using Android.
The com.amazonaws:ivs-chat-messaging
package implements the interface
described in this document.
Latest version of IVS Chat Client Messaging Android SDK: 1.1.0 (Release Notes)
Reference documentation: For information on the most
important methods available in the Amazon IVS Chat Client Messaging Android SDK, see the
reference documentation at: https://aws.github.io/amazon-ivs-chat-messaging-sdk-android/1.1.0/
Sample code: See the Android sample repository on GitHub:
https://github.com/aws-samples/amazon-ivs-chat-for-android-demo
Platform requirements: Android 5.0 (API level 21) or greater is required for development.
Getting Started
Before starting, you should be familiar with Getting Started with Amazon IVS Chat.
Add the Package
Add com.amazonaws:ivs-chat-messaging
to your
build.gradle
dependencies:
dependencies { implementation 'com.amazonaws:ivs-chat-messaging' }
Add Proguard Rules
Add the following entries to your R8/Proguard rules file
(proguard-rules.pro
):
-keep public class com.amazonaws.ivs.chat.messaging.** { *; } -keep public interface com.amazonaws.ivs.chat.messaging.** { *; }
Set Up Your Backend
This integration requires endpoints on your server that talk to the Amazon IVS
API. Use the official AWS
libraries
Next, create a server endpoint that talks to the Amazon IVS Chat API and creates a token.
Set Up a Server Connection
Create a method that takes ChatTokenCallback
as a param and fetches a
chat token from your backend. Pass that token to the onSuccess
method
of the callback. In case of error, pass the exception to the onError
method of the callback. This is needed to instantiate the main ChatRoom
entity in the next step.
Below you can find sample code that implements the above using a
Retrofit
call.
// ... private fun fetchChatToken(callback: ChatTokenCallback) { apiService.createChatToken(userId, roomId).enqueue(object : Callback<ChatToken> { override fun onResponse(call: Call<ExampleResponse>, response: Response<ExampleResponse>) { val body = response.body() val token = ChatToken( body.token, body.sessionExpirationTime, body.tokenExpirationTime ) callback.onSuccess(token) } override fun onFailure(call: Call<ChatToken>, throwable: Throwable) { callback.onError(throwable) } }) } // ...
Using the SDK
Initialize a Chat Room Instance
Create an instance of the ChatRoom
class. This requires passing
regionOrUrl
, which typically is the AWS region in which your chat
room is hosted, and tokenProvider
which is the token-fetching method
created in the previous step.
val room = ChatRoom( regionOrUrl = "us-west-2", tokenProvider = ::fetchChatToken )
Next, create a listener object that will implement handlers for chat related
events, and assign it to the room.listener
property:
private val roomListener = object : ChatRoomListener { override fun onConnecting(room: ChatRoom) { // Called when room is establishing the initial connection or reestablishing connection after socket failure/token expiration/etc } override fun onConnected(room: ChatRoom) { // Called when connection has been established } override fun onDisconnected(room: ChatRoom, reason: DisconnectReason) { // Called when a room has been disconnected } override fun onMessageReceived(room: ChatRoom, message: ChatMessage) { // Called when chat message has been received } override fun onEventReceived(room: ChatRoom, event: ChatEvent) { // Called when chat event has been received } override fun onDeleteMessage(room: ChatRoom, event: DeleteMessageEvent) { // Called when DELETE_MESSAGE event has been received } } val room = ChatRoom( region = "us-west-2", tokenProvider = ::fetchChatToken ) room.listener = roomListener // <- add this line // ...
The last step of basic initialization is connecting to the specific room by
establishing a WebSocket connection. To do this, call the connect()
method within the room instance. We recommend doing so in the onResume()
lifecycle method to make sure it keeps a connection if your app resumes from
the background.
room.connect()
The SDK will try to establish a connection to a chat room encoded in the chat token received from your server. If it fails, it will try to reconnect the number of times specified in the room instance.
Perform Actions in a Chat Room
The ChatRoom
class has actions for sending and deleting messages and
disconnecting other users. These actions accept an optional callback parameter that
allows you to get request confirmation or rejection notifications.
Sending a Message
For this request, you must have the SEND_MESSAGE
capability
encoded in your chat token.
To trigger a send-message request:
val request = SendMessageRequest("Test Echo") room.sendMessage(request)
To get a confirmation/rejection of the request, provide a callback as a second parameter:
room.sendMessage(request, object : SendMessageCallback { override fun onConfirmed(request: SendMessageRequest, response: ChatMessage) { // Message was successfully sent to the chat room. } override fun onRejected(request: SendMessageRequest, error: ChatError) { // Send-message request was rejected. Inspect the `error` parameter for details. } })
Deleting a Message
For this request, you must have the DELETE_MESSAGE capability encoded in your chat token.
To trigger a delete-message request:
val request = DeleteMessageRequest(messageId, "Some delete reason") room.deleteMessage(request)
To get a confirmation/rejection of the request, provide a callback as a second parameter:
room.deleteMessage(request, object : DeleteMessageCallback { override fun onConfirmed(request: DeleteMessageRequest, response: DeleteMessageEvent) { // Message was successfully deleted from the chat room. } override fun onRejected(request: DeleteMessageRequest, error: ChatError) { // Delete-message request was rejected. Inspect the `error` parameter for details. } })
Disconnecting Another User
For this request, you must have the DISCONNECT_USER
capability
encoded in your chat token.
To disconnect another user for moderation purposes:
val request = DisconnectUserRequest(userId, "Reason for disconnecting user") room.disconnectUser(request)
To get confirmation/rejection of the request, provide a callback as a second parameter:
room.disconnectUser(request, object : DisconnectUserCallback { override fun onConfirmed(request: SendMessageRequest, response: ChatMessage) { // User was disconnected from the chat room. } override fun onRejected(request: SendMessageRequest, error: ChatError) { // Disconnect-user request was rejected. Inspect the `error` parameter for details. } })
Disconnect from a Chat Room
To close your connection to the chat room, call the disconnect()
method on the room instance:
room.disconnect()
Because the WebSocket connection will stop working after a short time when the
application is in a background state, we recommend that you manually
connect/disconnect when transitioning from/to a background state. To do so, match
the room.connect()
call in the onResume()
lifecycle
method, on Android Activity
or Fragment
, with a
room.disconnect()
call in the onPause()
lifecycle
method.