What's the android preferable way of spawning a new thread?

Go To StackoverFlow.com

1

Coming from the basic Java world I know there's a way to spawn a thread by creating a new Runnable and passing it to a new Thread and calling start on it. Something like:

Runnable r = new Runnable() {
   @Override
   public void run(){
   }
}

new Thread( r ).start()

Now joining the Android world it seems the Android eco system provides a few other ways to spawn a thread. One of them is Activity.runOnUiThread (for having stuff done on the UI) and Handler.post( runnable ).

What I am wondering about is what's the Android preferable way of spawning a new thread. I do see a lot cases such as:

Handler handler = new Handler()
handler.post( r )

Is there a good reason to use Handler to spawn a thread as opposed to creating a new Thread old way?

Thanks. Yev

2012-04-04 18:50
by ymotov


2

Check out the AysncTask framework. It seems like that's how Google wants you to handle threads...although you can use standard java threading.

2012-04-04 18:52
by Chris Thompson
Absolutely correct. Here's a great tutorial that discusses Android "Threads", "Async Tasks" and "Handlers": http://www.vogella.de/articles/AndroidPerformance/article.htm - paulsm4 2012-04-04 18:54
Thanks... that explains some of my concerns - ymotov 2012-04-06 14:18


1

The Handler in the way you've demonstrated doesn't actually spawn a new thread. Handlers are not threads, but are rather a means of IPC to let one thread tell another thread to run code. You still spawn off threads in the same old way, but the Handler helps those threads communicate better.

Say, for example, you have a Thread that you've spawned off in the background in the usual way:

Runnable r = new Runnable() {
   @Override
   public void run(){
   }
}

new Thread( r ).start()

It runs in the background doing processing, but it needs to update the UI with it's progress, so it calls back to the Activity:

onProgress(int progress) {
  // update UI
}

If you run that code as is, it will throw an exception, because only the UI thread is allowed to update the UI. Handlers can solve that problem like so:

public void onProgress(int results) { mHandler.post(new UIUpdater(results)); }

private class UIUpdater implements Runnable {
  UIUpdater(int results) {
    //construct whatever...
  }

  @Override
  public void run() {
    //Update UI
  }
}

Alternately, you can have Android manage Threads and Handlers for you through the AsyncTask framework

2012-04-04 18:59
by JRaymond
Thanks JRaymond... I think AsyncTask is what I was looking for - ymotov 2012-04-06 14:18


0

Handler is not supposed to spawn thread , but to post new task to UI thread. IMO the way to spawn thread is the java way, through runnable or extended thread directly. The android guys wrapped an Executor around the Async task and exposed some method that run directly in UI thread, and one to run your task in background.

2012-04-04 18:57
by Blackbelt
Ads