reiley reiley - 26 days ago 10
Android Question

When to use handler.post() & when to new Thread()

I'm wondering when to use

handler.post(runnable)
& when to use
new Thread(runnable).start();


It is mentioned in developers doc:


Causes the Runnable r to be added to the message queue. The runnable
will be run on the thread to which this handler is attached.


Does this mean if in the
onCreate
of
Activity
class I write:

Handler handler = new Handler()
hanlder.post(runnable);


then, runnable will be called in a seperate thread or on the Activity's thread?

Thank You

Answer

You should use Handler.post() whenever you want to do operations in the UI thread.

So let's say in the callback (which is running in separate thread) you want to change a TextView's text, you should use Handler.post().

In Android, as in many other UI frameworks, UI elements (widgets) can be only modified from main thread.


Edit: the example of long-running tasks

mHandler = new Handler();

new Thread(new Runnable() {
  @Override
  public void run () {
    // Perform long-running task here
    // (like audio buffering).
    // you may want to update some progress
    // bar every second, so use handler:
    mHandler.post(new Runnable() {
     @Override
     public void run () {
       // make operation on UI - on example
       // on progress bar.
     }
    });
  }
}).start();

Of course, if the task you want to perform is really long and there is a risk that user might switch to some another app in the meantime, you should consider using a Service.