Why use HandlerThread in Android

前端 未结 6 1621
名媛妹妹
名媛妹妹 2020-12-14 09:43

In android , Handler can be used to post / handle message, if I don\'t use a HandlerThread (pass its Looper to Handler), does that mean in this case Handler use MainThread (

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 10:29

    if I don't use a HandlerThread (pass its Looper to Handler),does that mean in this case Handler use MainThread (UI Thread) 's Looper ?

    Have a look at documentation of Handler

    Handler ()
    

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

    If your current thread is MainThread, it uses MainThread(UI Thread) Looper.

    To explicitly associate Handler to your MainThread ( UI Thread), write below code.

    Handler  mHandler = new Handler(Looper.getMainLooper();
    

    If you write is as below, it uses HandlerThread Looper.

    HandlerThread handlerThread = new HandlerThread("HandlerThread");
    handlerThread.start();
    Handler requestHandler = new Handler(handlerThread.getLooper());
    

    If you have any network IO operation in Runnable task, you can't use Main thread looper. In that case, HandlerThread is handy to post Runnable task performing Network IO operation.

    You can find example code @ How do I fix android.os.NetworkOnMainThreadException?

    What result will get if Handler uses MainThread's Looper ? May cause mainThread blocked ?

    If you send many events to MainThread Looper, they will execute on MainThread (UI Thread) itself. If there submitted tasks are taking more time for execution, MainThread will be blocked.

    Check below post for internals of Looper:

    What is the purpose of Looper and how to use it?

提交回复
热议问题