Sobes.tech
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:

  1. Polling — the app periodically sends requests to the server to get new messages.

  2. Long Polling — the client sends a request that the server keeps open until new messages appear, then responds.

  3. WebSocket — a persistent bidirectional connection is established, through which the server can send new messages at any time.

  4. 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)