Search code examples
androidhandler

Use of Handler Android


Which is the better way to use a handler. Any advantages. All examples I have come across seem to give the inline version.

Using implements Handler.Callback in the class and implementing interface method.

or

Using inline code version

private Handler mHandler = new Handler(){ ....};

Solution

  • The common term or these inline class definitions is Anonymous Classes.

    You can read more about the discussion on these in Java/Android: anonymous local classes vs named classes

    Essentially the main differences are readbility, speed of coding, re-use and scope.

    From a resource point of view the anonymous class creation may cause an overhead in the garbage collector as discussed in Avoid Creating Unnecessary Objects. I am not certain on the exact details of anonymous class creation, however, it is logical that implementing the interface on the class is more efficient.

    @WilliamTMallard has provided an example of what NOT to do. In his example, a long and syntacticly complex handler should be implementented on the class rather than anonymous handler because it is harder to read and edit when defined inline.