SyncAdapter to receive chat messages?

475 views Asked by At

For my chat app I am looking for a good way to sync messages while the app is in background.

At the moment I have a websocket. When the app comes to foreground, messages get synced. This makes the app looking laggy. Like WhatsApp I need a way to have all messaged synchronized before the app gets in foreground.

I thought about the following solution: I set up a SyncAdapter which gets triggerd by a push notification ("new message for chat xy"). Then inside the SyncAdapter I fetch new messages.

Now the problem is I do not want to connect (e.g. via REST) for each line which has been written. And also I don't want to wait x minutes to bundle new messages.

As I said before, I already have a websocket which gets established when the app goes to foreground. Is it a good idea to move this code to the SyncAadapter? Can I keep the connection open there or should I close it if I dont receive a message for x minutes? The only problem I see is, if an user is not able to receive push messages.

If anyone knows of famous chat apps do it, please point me to this direction.

1

There are 1 answers

4
pfmaggi On

Signal (secure messaging app) is opensource. You can take a look at how they implemented a real-world solution with the goal of implementing a very secure chat.

Depending of what is your main goal you can choose a simpler implementation with available pieces. However I think that you still need a few pieces:

  1. A push system to wake up your application when a new message is available
  2. A way to retrieve the message when the app is in background
  3. A system that monitor network and retries sending a message as soon network is back

The first item can be solved with Firebase Cloud Messaging (FCM) the second and third can be implemented with WorkManager.

I would avoid to keep something on the device with an open connection to check for new messages for two main reasons:

  • battery consumption
  • background restrictions