IntentService connected to server listening

I encoded the IntentService where I am sending the command line. Associated with the activity in which I am trying to program the console. The purpose of the action is to execute a "command line" where I can send and receive to / from the server.

Service Action:

  • CONnect to the server
  • Send command line
  • Get an answer
  • Get response to user

The main problem is that every time I send the command line, the Service must reconnect to the server. (The reason every time the whole service starts) How can I avoid this step?

I would like to “support” a service that is waiting for a command line to be sent without having to reconnect every time I perform its action.

Is there a way to make this responsive? I mean, I start the service and every time I set its action (setAction), and put the line I want (putExtra). Then do I need to start the service again?

Good night. I'll be back tomorrow :)

Thanks in advance!

+1
source share
2 answers

Due to its one-shot design, using IntentService not a good approach to IMO.

If you do not want to start the service every time you send a command, then I suggest that you “bind” it to the Service standard (see Related Services ). If you bind to Service in your Activity onResume() method and onPause() in onPause() , your Activity will be able to directly call methods in Service .

You, of course, will need to create your own worker Thread in your Service to handle any work related to your network connection. If you want any tips on how to do this, check out the source code for IntentService - it's pretty straight forward.

+1
source

Do not use IntentService . Per documentation :

the service starts as needed, processes each Intent in turn using the workflow, and stops when work ends.

Instead, you should use the regular Service (call stopSelf () ) when you want to stop the service (and your connection to the server). Or, if you want the connection to the server to have the same life cycle as the action, you can create a related service : it will start when your activity contacts it, and then stop when the last activity is not connected.

+1
source

All Articles