开发者

Handler or Listeners. What is better?

Handler or Listeners. What is开发者_开发百科 better use for notification of event? What is faster, more efficient etc.?


That's a good question!

scenario for using a handler

I've got an Android background service running in my app that uses handlers exclusively for web communications - I decided to go this route because the handler will queue requests and execute them one by one so then I know that a sequence is remained intact.

For example, in an instant messenger app you might find it desirable to maintain a sequence for your chatting.

scenario for using a callback

My background service also uses a class that reads from hardware (in a separate thread); some data might come in at any time and needs to be processed immediately. For that class I implemented a listener/callback interface.


My only question is whether there's any etiquette for the size of the handler. I have about 50 unique messages:

  • outgoing web requests consists of about 25 messages (each message is a different API on the web server)
  • Each API returns a response, therefore there's another 25 incoming web responses

The handler requires about 60% of the service's code - as you can imagine this results in a very big switch(case{}) structure (almost 1000 lines of code). Too big? How to break it apart?


There's no such thing as a Listener type, it's just a naming convention for callback interfaces. So you just use them if you want to process your events synchronously on the same thread.

A Handler is however an Android class... you use it for passing messages and runnables from the thread raising the event (e.g. "download complete") to the thread that needs to handle it (e.g. the UI thread).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜