看了多位大神的源码解析,为了加深自己的理解,遂将自己跟走一遍的流程记录于此
Handler机制:一种异步消息处理机制,在项目中常用于更新主线程UI,也可在项目中做一些延时等操作
我们先看一下项目中如何使用
class SecondActivity :AppCompatActivity(){
var mTextView:TextView? = null
private val mHandler = MHandler(WeakReference(this))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mTextView = findViewById(R.id.tv)
val btn = findViewById<Button>(R.id.btn)
btn.setOnClickListener {
Thread(Runnable {
val msg = Message()
msg.what = 1
msg.obj = "it's time"
mHandler.sendMessage(msg)
}).start()
}
}
internal class MHandler(reference: WeakReference<SecondActivity>) : Handler() {
private var activity: SecondActivity? = null
init {
activity = reference.get()
}
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
if(msg.what == 1){
val obj:String = msg.obj as String
activity?.mTextView?.text = obj
}
}
}
}
Handler机制的实现有几个重要的组成:
- Message:消息体,从上面的例子中我们可以看到,这个即我们需要传递的消息
- Handler:消息的传递者和处理者,在上方的例子中,通过handler.sendMessage发送消息,在handlermessage中处理消息
- Looper:轮询器,不断从消息队列中取出消息
- MessageQueue:消息队列,采用单链表结构存储消息,便于插入和删除消息
了解了这几个之后,我们从源码走一遍消息发送的流程
- 首先进入到handler的构造方法中
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
klass.getCanonicalName());
}
}
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread " + Thread.currentThread()
+ " that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}
从代码中我们能看到handler构造函数需要一个looper对象,而looper对象需要我们自己调用Looper.prepare()来构建
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));
}
从代码中我们能看到一个线程只能有一个looper对象
我们在主线程创建handler不需要先创建该对象是由于在main函数中已经由系统帮我们创建了
public static void main(String[] args) {
//
Looper.prepareMainLooper();
ActivityThread thread = new ActivityThread();
//
Looper.loop();
}
public static final void prepareMainLooper() {
prepare();
setMainLooper(myLooper());
if (Process.supportsProcesses()) {
myLooper().mQueue.mQuitAllowed = false;
}
}
- 将消息加入到消息队列
public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
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;
}
return enqueueMessage(queue, msg, uptimeMillis);
}
private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}
其中的queue即是我们在创建looper时创建的,到了这一步之后就是调用MessagqQueue的方法将消息加入到消息队列中
boolean enqueueMessage(Message msg, long when) {
if (msg.target == null) {
throw new IllegalArgumentException("Message must have a target.");
}
if (msg.isInUse()) {
throw new IllegalStateException(msg + " This message is already in use.");
}
synchronized (this) {
if (mQuitting) {
IllegalStateException e = new IllegalStateException(
msg.target + " sending message to a Handler on a dead thread");
Log.w(TAG, e.getMessage(), e);
msg.recycle();
return false;
}
msg.markInUse();
msg.when = when;
Message p = mMessages;
boolean needWake;
if (p == null || when == 0 || when < p.when) {
// New head, wake up the event queue if blocked.
msg.next = p;
mMessages = msg;
needWake = mBlocked;
} else {
// Inserted within the middle of the queue. Usually we don't have to wake
// up the event queue unless there is a barrier at the head of the queue
// and the message is the earliest asynchronous message in the queue.
needWake = mBlocked && p.target == null && msg.isAsynchronous();
Message prev;
for (;;) {
prev = p;
p = p.next;
if (p == null || when < p.when) {
break;
}
if (needWake && p.isAsynchronous()) {
needWake = false;
}
}
msg.next = p; // invariant: p == prev.next
prev.next = msg;
}
// We can assume mPtr != 0 because mQuitting is false.
if (needWake) {
nativeWake(mPtr);
}
}
return true;
}
我们可以看到消息队列是按照时间通过指定下一个next来完成入队的操作,当我们使用sendMessageAtFrountOfQueue()发送消息,msg.when = 0,就会添加到消息队列头部
- 将消息从消息队列中取出
public static void loop() {
final Looper me = myLooper();
if (me == null) {
throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
}
final MessageQueue queue = me.mQueue;
//
for (;;) {
Message msg = queue.next(); // might block
if (msg == null) {
// No message indicates that the message queue is quitting.
return;
}
//
//
try {
msg.target.dispatchMessage(msg);
dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}
msg.recycleUnchecked();
}
}
代码挺多,留下了重要的几行,我们能看到在loop方法中是一个死循环,我们调用next()方法从消息队列中取出消息,当有消息时会通过msg.what.dispatchMessage来进行分发,而msg.what我们在之前的handler的enqueueMessage方法中能发现就是发送消息的handler,这样来分发到对应的处理者
- 处理消息
我们再回到handler的方法中
public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}
我们能看到有几个不同的回调,这些之后会说到。这里我们看到最后一行代码handleMessage()该方法就是我们在activity中进行实现的方法。至此一套完整的消息传递粗粗走完。
由于Handler是依附于创建的线程,所以此后我们的handlermessage方法处于主线程中,可以进行ui操作
盗取郭神示意图:
再看下其他几个子线程更新ui的方法
- handler的post方法
btn.setOnClickListener {
Thread(Runnable {
mHandler.post { mTextView?.text = "it's time"}
}).start()
}
往下走一会
public final boolean post(Runnable r)
{
return sendMessageDelayed(getPostMessage(r), 0);
}
public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
}
能看到只是将runnable对象作为msg进行消息传递,和之前没有什么区别
private static Message getPostMessage(Runnable r) {
Message m = Message.obtain();
m.callback = r;
return m;
}
由此我们联想到dispatchMessage中的callback中的来源
- View的post方法
btn.setOnClickListener {
Thread(Runnable {
mTextView?.post { mTextView?.text = "it's time" }
}).start()
}
往里看下
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().post(action);
return true;
}
能看到调用的是handler的post方法
- runOnUiThread()
btn.setOnClickListener {
Thread(Runnable {
runOnUiThread {
mTextView?.text = "it's time"
}
}).start()
}
往里看看
public final void runOnUiThread(Runnable action) {
if (Thread.currentThread() != mUiThread) {
mHandler.post(action);
} else {
action.run();
}
}
也是调用了handler的post方法
粗粗走过,未求甚解~~~