mccolo
mccolo

Reputation: 13

Sockets and multithreading with Android

I'm trying to allow two threads in an Android application to communicate with each other. Simple, right? I have two threads:

At the moment, in order for Thread A to send messages to Thread B, I'm using a class with static instance data and static methods that can be set by Thread A. Thread B is using a loop to check for incoming data over the socket, so I used the same loop to check for a change in that supplementary class. That's how I managed to send data from Thread A to Thread B. However, I'd also like Thread B to be able to notify Thread A, the main user interface thread, that the socket has been closed, and act on that. Unfortunately though, Thread A isn't using any loops to check something continuously. So my question is, how do I notify Thread A of a change in Thread B? I've done searches and found that the Observer pattern would be useful, but I'm not sure that I can bring the Observer pattern into my existing setup. Any help or guiding thoughts would be much appreciated! Thanks.

Upvotes: 1

Views: 1417

Answers (1)

d370urn3ur
d370urn3ur

Reputation: 1746

Instantiate a handler in your UI Thread (Thread A), and pass a reference of the handler to Thread B. When you want to notify Thread A of something, create a Message object and use the handler to sendMessage().

Example of a very simple pattern here

Check official docs for Handler and Message classes

google for Android handler tutorial

Upvotes: 2

Related Questions