zoukankan      html  css  js  c++  java
  • Handler队列

    Handler 
    1. 作用:消息队列  线程队列 
    2. 重点: 
    Handler调用Runnable实际是并不是开新线程 而是放入自己的线程中。 
    如果要开启线程 需要使用handlerThread获得looper对象并绑定到handler对象上。 
    3. 使用:  
    线程队列 
    1. 先创建一个handler对象 
    2. 将要执行的动作写入线程的run中。(handler线程队列放入的是线程(Runnable|thread)) 
    3. 调用handler的post方法把将要执行的线程对象加添进线程队列。 
    EX:如果想线程不断执行的话可以自run方法中加入handler.post/postDelayed调用当前的runnable,实现递归(也就是执行的方法体中 直接会间接的重新调用自己的方法实现不断的循环执行此方法)。 

    消息队列 
    1. 通过给new handler 覆写 
    public void handleMessage(Message msg) 

               …… 

    来实现接受message信息 
    2. 通过handler对象.obtainMessage来获得Mesaage对象 
    Message msg=updateHandler.obtainMessage(); 
    3. 通过handler对象.sendMessage(Message msg)来发送message到消息队列 
    handler对象.sendMessage(msg) 
    然后将message加入到消息队列(先进先出)被handleMessage接收。 
    PS:创建handler时 复写handleMessage 方法(匿名内部类|继承handler的类 复写handleMessage) 
    4. 如果要实现递归则吧发送放入线程然后每次就收到message都将线程再放入线程队列。(可用于实现进度条ProgressBar变化) 

    4. handler 与 handlerThread 
    说明: 
    1.因为handler post入Runnable对象其实是没用创建新的线程的。所以android提供了handlerThread来弥补。 
    2.hanlderThread可以提供looper对象。Looper对象是用来循环处理消息队列的。 
    3.hanlderThread需要Start来开启。 
    4.开启后获取looper对象(必须start后获取looper否则会为空) 并把handler绑定到looper 对象上(通过handler有参构造), 
    Looper就会按照handler的handleMessage处理消息队列了。 
    5.这样handler就在looper的所在的线程中执行了。 

    5.在handler中使用message 
    通过 handler对象 . obtainMessage()方法获得message 对象。 
    发送message对象时有两种: 
    1.handler对象.sendMessage(msg);  //发送给handler对象 
    2.msg对象. sendToTarget();    //发送给创建msg的对象 

    6.Message携带数据 
    Msg.arg1; 只能携带int。 
    Msg.obj;  携带obj对象。 
    Msg.setDate(Bundle x)携带Bundle对象。 

    7.Bundle 束 
    Bundle对象类似于HashMap 
    不同的是HashMap的键是任意的。 
    而bundle的键必须是stiring 
    放入数据 
    Bundle temp=new Bundle(); 
    temp.putString("name", "wenxiu"); 
    temp.putInt("age", 19); 
    读取数据 
    Bundle temp_h=msg.getData(); 
    String name=temp_h.getString("name") 
    Int i=temp_h.getInt("age") 

  • 相关阅读:
    robotframework-ride1.7.3.1更新安装
    批量删除新浪微博
    Redis
    GET和POST两种基本请求方法的区别
    selenium2自动化测试实战--基于Python语言
    同步/异步/阻塞/非阻塞/BIO/NIO/AIO
    HTTP抓包实战
    LCT模板(BZOJ2631)
    树链剖分模板(BZOJ3083)
    凸包(BZOJ1069)
  • 原文地址:https://www.cnblogs.com/Gaojiecai/p/2229706.html
Copyright © 2011-2022 走看看