Android Activity Lifecycle for Server Connections Optimization

Viewed 29

I'm developing an app with chat as a mini feature. I've two chat screens one for conversations listing lets call it ActivityA and other for actual message sending and reading lets call it ActivityB. The problem is that my chat server can only handle a limited number of concurrent open connections. So, to optimise connections, I'm trying to only connect when user is at any of chat screens and disconnect as soon as the chat screens go away i.e. stoped. For this, I tried using Activity's lifecycle methods onStart and onStop. I connect on onStart and disconnect on onStop. The problem is that the onStop ActivityA is called after onStart of ActivityB. Hence when user lands on ActivityB the connection get dismissed and no message can be sent. How can I fix this issue, please help?

2 Answers

A better approach to solve this issue would be to use a global state. I.e.: connect to the server once and use the same connection in both activities. This can be done using the Application class. Refer to this Link for more details and examples.

But basically what is going to happen is that you have the connection objects inside of the globalState (Can be any name), and you will access it from ActivityA and ActivityB. Thus you wouldn't have to connect to the server again.

You can probably do your connect/disconnect in onResume() and onPause(). These will also be called in each Activity, so to avoid breaking things I would delay the disconnect and cancel it if onResume() is called within a reasonable amount of time. Something like this:

in onPause():

  • Schedule a Runnable to disconnect in 500msec

in onResume():

  • Cancel any disconnect Runnable
  • Connect to server
Related