Android基础之十六Handle机制

来源:互联网 发布:量子工作室 知乎 编辑:程序博客网 时间:2024/06/10 18:16

Android基础之十六Handle机制

一:

那么Handle到底是干嘛用的呢? 

  1.创建handle实例
new Handle();
2.发送信息载体(Message)
sendMessage(msg);
3.处理消息
handleMessage(Message msg){};

主要接受子线程发送的数据, 并用此数据配合主线程更新UI.handler的消息队列机制,即通过handler中一个线程向消息队列中用sendMessage方法发送消息,发送的消息当然可以用来传递参数。在handler中用handleMessage来处理消息,处理方法是获得消息队列中的消息参数,用这些参数来完成另外一些功能。

 解释: 当应用程序启动时,Android首先会开启一个主线程 (也就是UI线程) , 主线程为管理界面中的UI控件,进行事件分发, 比如说, 你要是点击一个 Button ,Android会分发事件到Button上,来响应你的操作。  如果此时需要一个耗时的操作,例如: 联网读取数据,    或者读取本地较大的一个文件的时候,你不能把这些操作放在主线程中,,如果你放在主线程中的话,界面会出现假死现象, 如果5秒钟还没有完成的话,,会收到Android系统的一个错误提示  "强制关闭".  这个时候我们需要把这些耗时的操作,放在一个子线程中,因为子线程涉及到UI更新,,Android主线程是线程不安全的,也就是说,更新UI只能在主线程中更新,子线程中操作是危险的. 这个时候,Handler就出现了.,来解决这个复杂的问题 ,    由于Handler运行在主线程中(UI线程中),  它与子线程可以通过Message对象来传递数据, 这个时候,Handler就承担着接受子线程传过来的(子线程用sedMessage()方法传弟)Message对象,(里面包含数据)  , 把这些消息放入主线程队列中,配合主线程进行更新UI。 
二.原理浅析
new Handle():这个操作将生成一个Handle实例,handle实例有三个属性mLooper、mQueue
mCallback,
 mLooper = Looper.myLooper();        if (mLooper == null) {            throw new RuntimeException(                "Can't create handler inside thread that has not called Looper.prepare()");        }        mQueue = mLooper.mQueue;        mCallback = callback;        mAsynchronous = async;    }
sThreadLocal是一个单例对象,他的类型是ThreadLocal<Looper>,这个类有set()、get()方法,他的作用是当前线程的对象,那么这句代码的作用很明显了就是返回当前线程的Looper对象。再深入一点想,他的set方法在哪里呢?答案是在prepare中:
<span style="font-size:18px;">private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) {    throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed));}</span>
从该方法中可见每个线程中只可以调用一次prepare方法,即每个线程中只有一个Looper对象。
<span style="font-size:18px;"> mQueue = mLooper.mQueue;</span>
Looer对象的mQueue是一个非静态的变量

mCallback是一个回调接口,他只有一个方法handleMessage:
   public interface Callback {        public boolean handleMessage(Message msg);    }    
msg的生成;在Message类中我们看到有个Handle类型的target,所有发送到Handle的msg都会把这个target设置为当前的Handle,如sendMessage()方法最终会有这样一个操作
msg.target = this;
如果mCallback不为空就执行mCallback的handleMessage方法,否则执行自身的handleMessage方法
<span style="font-size:14px;"> public void dispatchMessage(Message msg) {        if (msg.callback != null) {            handleCallback(msg);        } else {            if (mCallback != null) {                if (mCallback.handleMessage(msg)) {                    return;                }            }            handleMessage(msg);        }    }</span>



0 0
原创粉丝点击