Socket listener in IntentService

1.2k views Asked by At

In my program, I am receiving data via socket in an IntentService class and then sending the same as a broadcast to activity. Activity processes the input and prepares an output.

while (true) {

            socket = serverSocket.accept();

            //Read data from socket

            //Publishing as a broadcast }

Now my question is

  1. How can I send the output from activity to the intentService? I know that I can fire a fresh intent to the intentService but since my while loop is already running in an infinite loop, won't this be queued and possibly never executed?
  2. Even if I manage to get data from activity to the intentService, how can I use the same socket connection to write back to the client or should I create a separate thread for the same?

Any insight would be helpful.

2

There are 2 answers

1
David Wasser On BEST ANSWER

IntentService is the wrong choice for this behaviour. You should use a regular Service and manage the threads and connections yourself.

You can then send data from an Activity to the Service either by calling startService() with an Intent containing the data, or you can have your Activity bind to the Service and use AIDL (remote procedure calls).

0
siva On

I think you should change your implementation as IntentService has only one thread and it is blocked with accept call. May be you should create two separate threads for accepting the connection and handling connected sockets. Using this approach you can easily share the data either using static objects or through broadcast receiver to the connected socket thread. Refer Bluetoothchat sample from android sdk.