I’m developing an application on android 3.1 and I have an Activity A that has a subclass extending from aSyncTask, this subclass create a socket and connect to a server. All my communication is good. I received messages and send commands to a server, but when I got a specific command I have to start a second activity (activity B) but I can’t lost my socket and the establish communication with the server, plus I have to still able to receive and send commands from activity B to server. How can I do that??
Any help please!
My approach is implementing a service and move/centralise all your network connection code into service, for all activities that want to use socket connection, bind your network service in onCreate() then after finish unbind it in onDestory()
According to Dianne Hackborn (Android engineer), the recommended practice to pass network connections between activities is to create a singleton that any activity can access and manage the connection from there. See here and check the first post by Dianne.
The Services page on the android developers site (side note under the ‘Basics’ Section) also mentions that you should only use a service if you need to run code that needs to continue execution while your application is in the background.