Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep socket connection between activities on android

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!

like image 897
Leonardo Arango Baena Avatar asked Oct 16 '11 08:10

Leonardo Arango Baena


2 Answers

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()

like image 170
yorkw Avatar answered Nov 19 '22 23:11

yorkw


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.

like image 34
CoatedMoose Avatar answered Nov 19 '22 22:11

CoatedMoose