I coded an IntentService where I send a command line. Is related to an activity where I'm trying to program a Console. The activity's purpose is to do a 'command prompt' where I can send and receive to/from the server.
The Service's action is:
- COnnect to the server
- Send command line
- Get response
- Retrieve response to user
The main problem is that every time I send a command line, the Service has to reconnect to the server. (Cause every time I'm starting the whole Service)How can I avoid this step?
I would like to "keep alive" the service waiting for a command line to send, without the need of reconnect every time I execute its action.
Is there any way to do it action-responsive? I mean, I start the service and every time I set its action (setAction) and put the line I want (putExtra). Then I have to start the service again?
Good night. Tomorrow I'll be back :)
Thanks in advance!
Don't use an
IntentService
. Per the documentation:Instead, you should consider using a normal
Service
(calling stopSelf()) when you want to stop the service (and your connection to the server). Or, if you'd like the connection to the server to have the same lifecycle as the activity, you can create a bound service: it will start when your activity binds to it and then stop when the last activity is unbound.Due to its "one shot" design, using an
IntentService
isn't a good approach IMO.If you don't want to start the service each time you send a command, then I'd suggest you 'bind' to a standard
Service
(see Bound Services). If you bind to theService
in yourActivity
'sonResume()
method and unbind inonPause()
yourActivity
will be able to directly call methods in theService
.You will, of course, have to create your own worker
Thread
in yourService
to handle any work involving your network connection however. If you want any tips on how to do that, look at the source code for IntentService - it's fairly straight-forward.