Why use Handler?

后端 未结 4 1850
傲寒
傲寒 2021-02-01 10:25

I came across this code in a very basic Handler tutorial. The code is working fine but I do not understand why I have to use Handler for progressDialog.dismiss()

4条回答
  •  心在旅途
    2021-02-01 10:51

    From the documentation of View:

    You must always be on the UI thread when calling any method on any view. If you are doing work on other threads and want to update the state of a view from that thread, you should use a Handler.

    In your example, when you've to call the dismiss() method on the ProgressDialog, as per the above documentation, you must do so from the UI thread. The messageHandler is initialized to an instance of a Handler when the HandlerThread class is instantiated (presumably on the UI thread).

    From the documentation of Handler:

    Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

    So to communicate with the UI thread from your new thread, just post a message to the Handler created on the UI thread.

    If you call methods on a View from outside the UI thread, it invokes undefined behaviour, which means, it may appear to work fine. But it's not always guaranteed to work fine.

提交回复
热议问题