Reputation: 933
I'm getting to a point in the development of an Android app where I've reached a stumbling block: how to create, manage, and connect to a Socket
in Android.
My app needs to keep a persistent TCP connection to the server in order to exchange JSON formatted strings back and forth. After reading up on the subject, I've determined the best way forward is to create a Service
when the app starts up (by extending the Application
class and starting the Service
in onCreate()
), then read from/write to the Socket
as needed. But how do I do that?
I obviously know how to create a Service
and how to create and work with a Socket
. But I don't know the best way to interact with one in an Android environment. Should I create an AsyncTask
whenever I want to write data? Should I use Intents
? Any help on the subject would be wonderful. And if my question isn't clear, I'll be more than happy to clarify anything.
Upvotes: 0
Views: 229
Reputation: 933
Apparently I was thinking about this problem incorrectly. What I need is to implement a "Bound Service", which will give my Activity
an interface to interact with in order to send and receive messages.
Here's a link to the tutorial I found which gives an excellent overview of how to do this.
Upvotes: 0
Reputation: 5632
Within the service, you can simply listen as you would in a regular Java application. This means you can safely wait for IO as you normally would.
You will have to use Intent
when you wish to notify your activities about new data arrival using sendBroadcast
and receiving it to your activities by either registering a BroadcastReceiver
using registerReceiver
or modifying your manifest file.
This is a good tutorial that may help you with broadcasting for Service <-> Activity communication.
Upvotes: 1