Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

performance - Android Activity Lifecycle for Server Connections Optimization

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...