Search code examples
androidandroid-handler

Difference between new Handler() and new Handler(Looper.myLooper())


I went through the official docs, but i can't seem to find if there is any difference between new Handler() and new Handler(Looper.myLooper())

new Handler()

Default constructor associates this handler with the Looper for the current thread.

Looper myLooper ()

Return the Looper object associated with the current thread. Returns null if the calling thread is not associated with a Looper.


Solution

  • From the Handler Source code, if you don't provide the looper, it'll by default operate on the current looper from which the Handler is initialized, i.e Looper.myLooper().

    So

    new Handler()

    and

    new Handler(Looper.myLooper())
    

    are basically the same.

    But the Handler(Looper looper) constructor can be used in situations where you want to change the thread other than the one from which the handle object is created.

    For example, if you are in background thread and want to run something on main thread, you won't be simply able to do it with new Handler() as that handler will operate in the same thread.

    Here you can use the constructor with Looper argument like:

    new Handler(context.getMainLooper())

    or

    Handler(Looper.getMainLooper()) //if you don't have context