Android Handler消息机制

来源:互联网 发布:欧洲卡车模拟2 知乎 编辑:程序博客网 时间:2024/05/22 08:41

Android消息机制主要是指Handler,MessageQueue和Looper的工作过程。

一、首先我们就来说说为什么Android会提供这个功能?

       这是因为Android规定访问UI只能在主线程中进行,如果在子线程中访问UI,程序就会报错。也正是由于这个原因导致我们必须在主线程中访问UI。但是Android又不建议在主线程中进行耗时操作,否则会导致程序无响应也就是ANR。而Hndler出现的原因,也主要是解决在子线程中无法访问UI的矛盾

       再说下为什么系统不允许在子线程中访问UI?这是因为Android的UI线程是线程不安全的。

二、Handler的工作过程
       当Handler创建完成之后,这时候其内部的Looper以及MessageQueue就可以和Handler一起协同工作了。

1.首先Handler先通过send方法发生一个消息。
2.当Handler的send方法被调用时,它会调用MessageQueue的enqueueMessage方法,MessageQueue的enqueueMessage方法会将这个消息放入到消息队列中。
3.然后Loopler发现有新消息到来时就会处理这个消息。
4.最后Handler的HandlerMessage方法就会被调用。

具体流程可以用下面的图来表示
这里写图片描述

三、Android消息机制分析

3.1消息队列的工作原理

       消息队列在Android中指的是MessageQueue,MessageQueue主要包含插入和读取两个操作。而读取和插入对应的方法分别为enqueueMessage和next。尽管MessageQueue叫消息队列,但是它内部实现并不是用的队列,实际上它内部是通过单链表来维护消息列表,原因是因为单链表在插入和删除上比较有优势。

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

上面是enqueueMessage方法的源码,它主要的操作就是单链表的插入操作。

Message next() {        // Return here if the message loop has already quit and been disposed.        // This can happen if the application tries to restart a looper after quit        // which is not supported.        final long ptr = mPtr;        if (ptr == 0) {            return null;        }        int pendingIdleHandlerCount = -1; // -1 only during first iteration        int nextPollTimeoutMillis = 0;        for (;;) {            if (nextPollTimeoutMillis != 0) {                Binder.flushPendingCommands();            }            nativePollOnce(ptr, nextPollTimeoutMillis);            synchronized (this) {                // Try to retrieve the next message.  Return if found.                final long now = SystemClock.uptimeMillis();                Message prevMsg = null;                Message msg = mMessages;                if (msg != null && msg.target == null) {                    // Stalled by a barrier.  Find the next asynchronous message in the queue.                    do {                        prevMsg = msg;                        msg = msg.next;                    } while (msg != null && !msg.isAsynchronous());                }                if (msg != null) {                    if (now < msg.when) {                        // Next message is not ready.  Set a timeout to wake up when it is ready.                        nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);                    } else {                        // Got a message.                        mBlocked = false;                        if (prevMsg != null) {                            prevMsg.next = msg.next;                        } else {                            mMessages = msg.next;                        }                        msg.next = null;                        if (DEBUG) Log.v(TAG, "Returning message: " + msg);                        msg.markInUse();                        return msg;                    }                } else {                    // No more messages.                    nextPollTimeoutMillis = -1;                }                // Process the quit message now that all pending messages have been handled.                if (mQuitting) {                    dispose();                    return null;                }                // If first time idle, then get the number of idlers to run.                // Idle handles only run if the queue is empty or if the first message                // in the queue (possibly a barrier) is due to be handled in the future.                if (pendingIdleHandlerCount < 0                        && (mMessages == null || now < mMessages.when)) {                    pendingIdleHandlerCount = mIdleHandlers.size();                }                if (pendingIdleHandlerCount <= 0) {                    // No idle handlers to run.  Loop and wait some more.                    mBlocked = true;                    continue;                }                if (mPendingIdleHandlers == null) {                    mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];                }                mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);            }            // Run the idle handlers.            // We only ever reach this code block during the first iteration.            for (int i = 0; i < pendingIdleHandlerCount; i++) {                final IdleHandler idler = mPendingIdleHandlers[i];                mPendingIdleHandlers[i] = null; // release the reference to the handler                boolean keep = false;                try {                    keep = idler.queueIdle();                } catch (Throwable t) {                    Log.wtf(TAG, "IdleHandler threw exception", t);                }                if (!keep) {                    synchronized (this) {                        mIdleHandlers.remove(idler);                    }                }            }            // Reset the idle handler count to 0 so we do not run them again.            pendingIdleHandlerCount = 0;            // While calling an idle handler, a new message could have been delivered            // so go back and look again for a pending message without waiting.            nextPollTimeoutMillis = 0;        }    }

上面是next方法的源码,我们可以发现next方法是一个无限循环的方法,如果消息队列中没有消息,那么next方法就会一直阻塞,如果有新的方法到来时,next方法就会返回这个消息并将其从单链表中移除

3.2Looper工作原理

       Looper在消息机制中它会不停的从MessageQueue中查看是否有新消息,如果MessageQueue中有新消息就会立刻处理,否则就会一直阻塞在那里。

Looper有一个最重要的方法就是loop方法,只有调用了loop方法以后,消息循环才会真正起作用,而Looper的loop方法的工作过程也很好理解,他和MessageQueue的next方法相似都是for(;;)的一个死循环,唯一跳出循环的方式是MessageQueue的next方法返回null,当Loop的quit方法被调用时,Looper就会调用MessageQueue的quit或者quitSafely方法来通知消息队列退出,当消息队列被退出时MessageQueue的next方法就会返回null,而如果MessageQueue的next方法返回了新消息Looper就会处理这条消息。

不知道大家在使用Handler的时候,如果有时候我们在子线程中使用Handler,那么就会报错,这是为什么呢?
       原因就是Handler工作需要Looper,如果没有Looper的线程就会报错,所以我们在子线程中使用Handler就需要创建Looper,我们可以通过Looper.prepare()方法创建一个Looper对象,然后通过Looper.loop()方法来开启消息循环,如下所示

    new Thread(){            @Override            public void run() {                super.run();                //创建Looper                Looper.prepare();                Handler hander = new Handler();                //开启消息循环                Looper.loop();            }        };

上面代码就是在子线程中创建一个Looper然后开启消息循环
那么有人会问为什么我们在主线程中使用Handler的过程中,我们没有创建Looper,但是使用Handler确可以正常使用呢?因为Looper除了提供prepare方法外还提供了prepareMainLooper方法,Android在主线程中已经处理了Looper,我们可以通过getMainLooper方法在任何地方获取到主线程的Looper,然后就可以使用quit方法退出Looper,这个是可以处理Handler中的内存泄漏问题的.

3.3Handler工作原理

Handler的工作主要包含消息的发送和接收过程,

Handler的消息发送:Handler消息发送可以通过post的一系列方法或者send的 一系列方法来实现,post的一系列方法最终通过send的一系列方法来实现,Handler的消息发送过程仅仅是向消息队列插入一条消息,MessageQueue的next方法就会将这条消息返回给Looper,然后Looper处理这条消息

Handler的消息处理:这里使用网上的一张状态图很好理解
这里写图片描述

好了这就是所有的Handler消息机制

0 0
原创粉丝点击