首页 > 系统 > Android > 正文

Android单排上王者系列之Handler机制分析

2019-11-09 16:10:51
字体:
来源:转载
供稿:网友

Handler机制分析

1.构造函数

Handler的构造函数有四个,在构造函数中获取了Looper对象和MessageQueue消息队列

每个Handler对应一个Looper对象和MessageQueue对象

让Handler处理消息有两种方法:

向Handler构造方法中传入Handler.Callback对象,并实现Handler.Callback的handleMessage方法无需向Hanlder的构造函数传入Handler.Callback对象,但是需要重写Handler本身的handleMessage方法

2.Handler发送消息

//发送消息 public final boolean sendMessage(Message msg) { //调用延时发送 return sendMessageDelayed(msg, 0); } //延时发送 public final boolean sendMessageDelayed(Message msg, long delayMillis) { if (delayMillis < 0) { delayMillis = 0; } //调用sendMessageAtTime return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis); } //sendMessageAtTime public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } //调用enqueueMessage return enqueueMessage(queue, msg, uptimeMillis); } //enqueueMessage PRivate boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { //设置设置msg.target为当前handler对象 msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } //将消息添加的消息队列中 return queue.enqueueMessage(msg, uptimeMillis); }

通过上述代码可以看出Handler发送消息有多种方式,但是最后都会调用sendMessageAtTime()方法,sendMessageAtTime()最后会调用enqueueMessage()方法,该方法会设置msg.target为当前的handler对象,并将消息添加到队列中。

所以创建Handler对象时只是得到了当前线程的Looper对象和MessageQueue队列,在handler对象发送消息的时候才会将设置target并且将消息添加到消息队列中。

3.Looper原理分析

Android在启动运行主线程main()方法的时候调用了Looper中的prepare()和looper()方法,为主线程事先创建了Looper对象并启动了消息循环。

prepare()方法流程

public static void prepare() { prepare(true); } private static void prepare(boolean quitAllowed) { //证了一个线程中只有一个Looper实例 if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } //通过ThreadLocal实现Looper实例和线程的绑定 sThreadLocal.set(new Looper(quitAllowed)); } //构造方法实例化当前的MessageQueue和当前线程 private Looper(boolean quitAllowed) { mQueue = new MessageQueue(quitAllowed); mThread = Thread.currentThread(); } public static MessageQueue myQueue() { return myLooper().mQueue; }

looper()方法流程

public static void loop() { final Looper me = myLooper(); //获取looper并且不能为空 if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { //for循环通过MessageQueue中的next()方法获取消息队列中的消息 Message msg = queue.next(); // might block if (msg == null) { return; } Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } //调用绑定的target也就是消息的handler对象执行对消息的处理 msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } }

Handler中的dispatchMessage()方法如下

public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }

在上述代码中可以看到消息最终被handler对象的handleMessage()方法处理了。

4.在子线程中使用Handler

因为子线程使我们手动创建的,并没有Looper和MessageQueue,所以需要我们自己创建。 在子线程中使用Handler需要三步

1.调用Looper的prepare()方法,为当前线程创建looper对象,然后将looper对象与当前线程绑定。在创建looper对象的时候会同时创建MessageQueue消息队列对象,这样Looper对象有了,MessageQueue对象也有了。然后重写handler对象的handleMessage()方法或者传入Handler.Callback对象重写其中的handleMessage()方法。调用Looper的looper()方法让循环启动起来通过队列中的next()方法获取消息然后调用handleMessage()处理消息。

5.总结

Handler:将消息发送给Looper管理的MessageQueue,处理Looper分发的消息Looper:每个线程只有一个Looper,负责管理对应的MessageQueue,并不断的从MessageQueue中取出消息交给handler处理。Android中主线程已经为我们创建好了Looper对象,所以可以直接使用handler发送和处理消息。应用自己创建的子线程需要调用Looper的prepare()方法来创建Looper对象和MessageQueue对象并将线程与Looper对象绑定,然后调用Looper的looper()循环从消息队列中取出消息分发给handler处理Message:消息对象MessageQueue:消息队列,它由Looper管理,通过先进先出的原则管理Message。Handler的构造方法会获取当前线程对应的Looper对象,并通过Looper对象获取MessageQueue对象。当Handler对象调用发送消息的时候会将自身赋给msg.target,并将消息加入的MessageQueue中。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表