7

Is there any problem with using multiple Handlers in the same Activity.

I noticed that in all samples provided in android official website they use a single handler and detect different actions depending on the value of "what", is this because of memory management, and high amount of memory used by the Handler? Or should I call it "bad code" and do it the clean way (Multiple handlers each responsible for a specific task)

Handler handler = new Handler()
{
    @Override
    public void handleMessage(Message msg) {
      if (msg.what == 0){
         // do something
      }
      else if (msg.what == 1){
         // do something else
      }
    }
}

OR

Handler taskHandlerA = new Handler()
{
    @Override
    public void handleMessage(Message msg) {
         // do something
    }
}

Handler taskHandlerB = new Handler()
{
    @Override
    public void handleMessage(Message msg) {
         // do something else
    }
}
Radi0actvChickn
  • 47
  • 1
  • 10
aryaxt
  • 76,198
  • 92
  • 293
  • 442
  • Well I wonder if a single handler is simpler to understand especially if you are using message based concurrency and do not want to worry about concurrent attempts read write to a shared memory counter with multiple handlers; instead with a single handler I suspect that all the messages must queue up and block in the handler. – JAL Jun 01 '11 at 03:15
  • I use the Handler as a replacement for Blocks. In C you can pass a block of code around and let it get called by external objects without doing delegation. And I figured I could achieve the same thing by using Handlers in Java. – aryaxt Jun 01 '11 at 03:37
  • Hi aryaxt... Seems reasonable and if you use a single handler the "block" variables in the Activity should be "handler safe" :) – JAL Jun 01 '11 at 05:20
  • Hmm. The more I think on this, all of the handlers probably run on the single GUI thread, so never mind. – JAL Jun 01 '11 at 06:25

2 Answers2

9

No there isn't such a limit (a Handler is just a message receiver), but if you want to do such a thing the more common approach is to have one Handler that you post Runnable objects to.

hackbod
  • 90,665
  • 16
  • 140
  • 154
5

Here is some good reading on Loopers and Handlers.

When a Handler is created, it is automatically registered with its' Thread's Looper. This makes me think that you do not need multiple Handler's for a single thread. An Activity, specifically, one that uses multiple Thread's, could use multiple Handler's though.

nicholas.hauschild
  • 42,483
  • 9
  • 127
  • 120