views:

387

answers:

2

I have a question about postDelayed. The android docs say that it adds the runnable to the queue and it runs in the UI thread. What does this mean?

So, for example, the same thread I use to create my layout is used to run the Runnable?

What if I want it as an independent thread that executes while I am creating my layout and defining my activity?

Thanks Chris

A: 

Yes that would run on the UI thread.

If you want to run a background thread then do it the normal way.

Thread t = new Thread(new Runnable(){});
t.start()

But if you want to change the UI at all in response to something that a background thread might do, then you can use postDelayed().

Any changes to the UI must be done on the main UI thread.

BrennaSoft
A: 

Congratulations! You found one of the places where there is more than one solution.

  1. Handlers, and PostDelayed can be nice lightweight ways of having your foreground activity called on a regular basis. Even the messages are reused. These are used in the Snake example program (Snake/SnakeView.java/sleep()) to make the snake move. It runs as 'post a message delayed by 500ms', in 500ms catch it in HandleMessage (the default for Handlers), move, then send it again. Even the message is reused with obtainMessage(). I've used these for making a button update while it is pushed down.

  2. Threads are a bit heavier. You might use these for background or where you are already used to running a thread. Make a 'new Thread(aRunnable).start()'. I haven't used them much on the Android.

  3. Launch an Intent with StartActivityForResult() and catch the result with OnActivityResult to make a standard RPC. See step 2 of the notepad example for more information.

  4. Look into more Intents to launch for different scenarios. I find putting your 'create and launch intent' into separate functions helps maintenance and debugging.

Good luck!

Charles Merriam