Matt
Matt

Reputation: 4989

Accessing Thread Started By Service

I'm having some trouble wrapping my head around this idea, and I wanted some input. I'm starting a service from my initial activity that runs a new thread (class that implements Runnable in this case, not extends Thread) in it's onCreate(). The thread first creates a TCP client socket, then begins sending requests and receiving responses every X seconds in the background as the app runs, activities switch, etc. I need to be able to access the thread from all of my activities however, to tell it to send out custom requests when UI elements are triggered. The service can be accessed from a static context, but when I try to access the running thread instance, I get errors related to performing network operations on main thread, which means it's not the actual instance, but the UI thread I'm accessing. I thought about implementing a message queue in the shared Application class that the service could poll for new messages, but that seems ugly. Maybe I'm going about this wrong and there is a better/cleaner way to approach this problem? Any advice or help would be greatly appreciated.

Upvotes: 1

Views: 316

Answers (1)

advantej
advantej

Reputation: 20325

You can use the Looper/Handler mechanism to send messages to the thread.

Upvotes: 1

Related Questions