title: Android: proper way to pass a message from background thread to UI thread?
body: <p>I have been reading a lot about threads, handlers, loopers, etc and I am very confused. In my app I want to have the first Activity start a background worker. This background worker will continually request data from a TCP socket and (hopefully) post the new info to the UI thread as the data arrives. If the user transitions to a new Activity the background needs to keep doing it's thing but only send different messages to the UI thread so it can update the new layout accordingly.</p>
  
  <p>here is what i have so far...This is in my main activity file</p>
  
  <pre><code>public class MyTCPTest extends Activity {
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          // set the layout
          setContentView(R.layout.main);
          // create a handler to handle messages from bg thread
          Handler handler = new Handler();
  
          BgWorkerThread bgw = new BgWorkerThread();
          bgw.start();
   }
  </code></pre>
  
  <p>in another file i define my background worker thread like this...</p>
  
  <pre><code>public class BgWorkerThread extends Thread {    
  @Override
  public void run(){
  
      while(true)
      {
          try {
          // simulate a delay (send request for data, receive and interpret response) 
          sleep(1000);
  
                      // How do I send data here to the UI thread?
  
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  } 
  </code></pre>
  
  <p>If the UI switches to a different Activity will this thread remain running? Also, how does the this thread know which activity to send the message to? Obviously I want it to always send the data to the Activity that is currently active. Does that happen automatically? </p>
  
  <p>Finally, when the UI switches to a different activity the bgworker needs to be notified so that it can begin requesting data that is relevant to the new Activity layout. What is the best way to inform the worker of the change? Couldn't I just create a public method in the BgWorkerThread class that could be called when Activities load?</p>