Maintain socket connections between actions on Android

I am developing an application on Android 3.1, and I have Activity A, which has a subclass extending from aSyncTask, this subclass creates a socket and connects to the server. All my message is good. I received messages and sent commands to the server, but when I received a certain command, I need to run the second action (activity B), but I can’t lose my socket and establish communication with the server, plus I still need to receive and send commands from the action B to the server. How can I do it?? Any help please!

+7
source share
2 answers

My approach implements service and moves / centralizes all your network connection code to the service, for all actions that want to use a socket connection, connects your service network in onCreate (), then after unbind it in onDestory ()

+13
source

According to Dianne Hackborn (Android developer), the recommended practice of transferring network connections between actions is to create a singleton mode with which any activity can access and control the connection from there. Take a look here and check out the first post from Dianne.

The Services page on the Android Developers site (note in the Basics section) also mentions that you should only use it if you need to run code that should continue to run while your application is in the background.

+10
source

All Articles