美文网首页
Looper 解析

Looper 解析

作者: heiheiwanne | 来源:发表于2017-05-04 15:13 被阅读22次
  1. Handler一定要在主线程实例化吗?new Handler()和new Handler(Looper.getMainLooper())的区别
    如果你不带参数的实例化:Handler handler = new Handler();那么这个会默认用当前线程的looper
    一般而言,如果你的Handler是要来刷新操作UI的,那么就需要在主线程下跑。
    情况:
    1.要刷新UI,handler要用到主线程的looper。那么在主线程 Handler handler = new Handler();,如果在其他线程,也要满足这个功能的话,要Handler handler = new Handler(Looper.getMainLooper());
    2.不用刷新ui,只是处理消息。 当前线程如果是主线程的话,Handler handler = new Handler();不是主线程的话,Looper.prepare(); Handler handler = new Handler();Looper.loop();或者Handler handler = new Handler(Looper.getMainLooper());
    若是实例化的时候用Looper.getMainLooper()就表示放到主UI线程去处理。
    如果不是的话,因为只有UI线程默认Loop.prepare();Loop.loop();过,其他线程需要手动调用这两个,否则会报错。

  2. Toast 内部是自己创建了Handler 所以在子线程中必须先Loop.prepare() 创建一个Looper,否则报错。


    IMG_0650.JPG

相关文章

网友评论

      本文标题:Looper 解析

      本文链接:https://www.haomeiwen.com/subject/jhjltxtx.html