Search code examples
android-serviceandroid-networking

service, threading and networking


I have been reading about services, executor, handler and I am still confused. I want a Thread to handle websocket protocol. I want any Activity to be able to use it to send a "command" and receive a reply to a callback. Each command will use a separate thread for network activity but use this websocket thread at the manager and initial reply handling.

[Send Cmd]: AnyActivity -> WebSocketThread -> NetThread -> SERVER [Recv Rply]:SERVER -> NetThread -> WebSocketThread -> AnyActivity.Callback

There may be any number of NetThreads at a time

I do not need code, but concepts on what Classes would be efficient and flexible. Also what is the most efficient way to pass the data: Intents; messages; ....?

** I use the term "thread" to mean separate threads that can run concurrently not the base class.


Solution

  • Implement a Service. The Service will own the websocket Thread and will start other Threads to handle individual requests.

    Activities call startService() to request the Service to do something. The calling Activity can pass data to the Service as extras in the Intent that is used in startService(). This Intent will be passed to method Service.onStartCommand().

    To pass data from the Service to the Activity there are several possibilities (depending on the type and amount of data that need to be returned). One choice is that the Service can broadcast the data as "extras" in a broadcast Intent using sendBroadcast() and the Activity can set up a BroadcastReceiver to listen for the response.