Sauron
Sauron

Reputation: 6647

Android Websocket Service Persistent Connection

I implemented a chat application in Android with websockets. However when the user closes the application, the websocket connection to the server is lost and no new messages can be received.

I am essentially lost and do not know where else to turn, how can I setup the service in the app to stay connected to the server as the user logs in as well as after the app has been stopped?

Upvotes: 4

Views: 2575

Answers (1)

urgentx
urgentx

Reputation: 3931

As we're all aware, continuous background code execution is not feasible on Android; different ROMs will man-handle your background services without any guarantees (e.g. START_STICKY will not get your service restarted on some devices), so we need to do the best we can with the code that is reliably executed.

In this situation, you have a websocket server delivering continous information to your client. When your app is in the background, it may miss out on some data. When your app returns to the foreground, your information may be out of sync, so you need to synchronize again with your server, and then reconnect to your websocket.

In my chat app I achieve this by checking whether my websocket service is running onResume in an activity which is a superclass of all the activities that I want to have access chatting data (i.e. not login/registration activities). If the service is not running, I synchronize my data by pulling the changes from an endpoint and then restarting the service. This way, even if the service is killed in the background I will still get the latest data and real-time experience once the app returns to the foreground.

Upvotes: 4

Related Questions