Junior — Middle
How can you request updated chat messages from the server?
sobes.tech AI
Answer from AI
To request updated messages in a chat on Android, the following approaches are usually used:
-
Polling — the app periodically sends requests to the server to get new messages.
-
Long Polling — the client sends a request that the server keeps open until new messages appear, then responds.
-
WebSocket — a persistent bidirectional connection is established, through which the server can send new messages at any time.
-
Firebase Cloud Messaging (FCM) — the server sends push notifications about new messages, after which the client requests updates.
An example of simple periodic polling using Handler:
val handler = Handler(Looper.getMainLooper())
val runnable = object : Runnable {
override fun run() {
// Request to the server to get new messages
fetchNewMessages()
handler.postDelayed(this, 5000) // repeat every 5 seconds
}
}
handler.post(runnable)