Help me in designing a better solution to sync chat messages between a single app user and server. If an app goes offline, i want to store messages in app database and push them to server when internet is available. And if at same time someone sends user a message, i want to properly arrange them based on time stamps. But are time tamps reliable in this scenario?
-
You can check [SyncAdapter](https://developer.android.com/training/sync-adapters/creating-sync-adapter.html) – hrskrs Mar 17 '17 at 07:22
1 Answers
Yes timestamps are reliable. But make sure you dont update the timestamps when a message that was in pending queue is sent.
A way to look forward to this is creating a broadcast manager and since you already have an app-db things can be easy.
Step 1: Create a BroadCastReceiver
to listen for network changes
A good SO post for the same can be found here where
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
is used to detect connectivity changes.
Step 2: Create int flags for your messages:
Where: assume: int
0 -> unsent
1-> sent
2-> read etc...
So whenever the user sends the message, check for the internet connectivity using this and if internet is not avail store to your app-local db with flag->0
else post to server
if you get a positive callback from the server save it as flag->1 else again with 0.
Step 3: Now in your onRecieve
method of your broadcast receiver, check if the changed status is a connected one (as in network connection is established) then pull from your db all messages which are saved with flag ->0
and resend them to the server with again the validations checks in step 2: just make sure you update them this time instead of recreating a new entry!
And that should be it!

- 1
- 1

- 2,134
- 14
- 27
-
My pleasure. Do try it and let me know if it you need any further help. Also if it works do mark it as an answer so others may find it useful! – MadScientist Mar 17 '17 at 09:26