11

I would like to know, once for all. I've read in many places. When I want do some 'long time operations' I should use a Handler.

But I don't get why? All my 'long-time-operations' I surround with a regular threads, and it works fine.

Why would I use Handler for this?

The only time I had to use Handler was, when I had to schedule some task(postDelayed)

Is there any main idea I miss about handlers(When I should really use it)? Or maybe there isn't really difference?

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
rayman
  • 20,786
  • 45
  • 148
  • 246

2 Answers2

16

A Handler lets you communicate back with the UI thread from your background thread. This is because UI operations are forbidden from within background threads. Note that starting at version 1.5, the AsyncTask class makes it much easier to do so.

JRL
  • 76,767
  • 18
  • 98
  • 146
  • 1
    So in other words, only when i wanna communicate my background thread with the UI, I should use Handler? – rayman Jun 23 '10 at 13:59
  • 2
    @rayman: if you need access to any UI component, you need a Handler - but if you're targeting API level 3 and above, AsyncTask makes the job easier for you. If you don't need access to the UI at all you don't need either and can just spawn a new Thread. – JRL Jun 23 '10 at 14:01
1

It can't just be about getting you back to the UI thread since runOnUiThread(Runnable) does that very nicely. I suspect this is more about making it easier for Android to manage threads and other resources that shouldn't live outside of an Activity's context, and that the "Activity has leaked..." exceptions tell you when that's happened.

Melinda Green
  • 2,100
  • 1
  • 21
  • 32