美文网首页
技能树-android基础-Handler消息机制

技能树-android基础-Handler消息机制

作者: 6faef730638b | 来源:发表于2018-04-20 18:06 被阅读9次

本质:一个线程开启循环模式持续监听并依次处理其他线程给它发的消息

成员介绍

1.Handler

消息的发送者和处理者
消息发送给Looper持有的MessageQueue
消息处理发生在handler所在线程

2.Looper

消息循环器,主要将MessageQueue中的message依次出队
并将其分发给target也就是handler

3.MessageQueue

存放消息message的队列
message可以存放硬件和软件产生的消息

机制运行

1.创建Handler关联Looper,Looper关联MessageQueue
2.handler发送消息给MessageQueue 入队 ,looper.loop循环取出message
3.looper分发给message对应的handler处理消息

原理解析

三者的关联

在使用的时候我们常在全局中

 private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {//重写 自己处理消息
            super.handleMessage(msg);
        }
    };

我们从构造方法入手看

public Handler(Callback callback, boolean async) {
 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;
}

Looper.prepare()是创建当前线程的looper的函数
从这里我们可以发现handler是无法在没有Looper的线程执行的
而app进程的主入口ActivityThread的main函数中我们可以发现

public static void main(String[] args) {
      
        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

     
        Looper.loop();
        throw new RuntimeException("Main thread loop unexpectedly exited");
    }
 public static void prepareMainLooper() {
        prepare(false);
        synchronized (Looper.class) {
            if (sMainLooper != null) {
                throw new IllegalStateException("The main Looper has already been prepared.");
            }
            sMainLooper = myLooper();
        }
    }

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那么这个handler对象
会持有主线程的Looper和此Looper循环的消息队列
就可以进行message的分发和处理了

模拟一次操作

handler.sendEmptyMessage()//发送空消息 会创建一个空消息的message对象

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);
    }

boolean enqueueMessage(Message msg, long when) {
synchronized (this) {
            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;
}

MessageQueue是以链队的形式组织message
handler发出的消息会入队进入

再来看Looper.loop();

for (;;) {
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            final long end;
            try {
                msg.target.dispatchMessage(msg);
                end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (slowDispatchThresholdMs > 0) {
                final long time = end - start;
                if (time > slowDispatchThresholdMs) {
                    Slog.w(TAG, "Dispatch took " + time + "ms on "
                            + Thread.currentThread().getName() + ", h=" +
                            msg.target + " cb=" + msg.callback + " msg=" + msg.what);
                }
            }

            if (logging != null) {
                logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);
            }

            // Make sure that during the course of dispatching the
            // 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();
        }

可以看出来是一个无限循环 将消息队列出队一个message对象
核心代码msg.target.dispatchMessage(msg);
这里的msg.target就是message对于->messagequeue对应的->Looper对应的handler
Handler target;

接着看dispatchMessage

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

分发消息有三种情况

1.如果message有回调 先处理回调 再执行我们重写的处理方法
2.message无回调但构造handler时有传入回调 那就只执行传入的回调
3.message无回调无handler构造传入回调 只执行我们重写的处理方法

End!

总结

图解消息机制

相关文章

网友评论

      本文标题:技能树-android基础-Handler消息机制

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