Android 消息机制笔记

来源:互联网 发布:英国脱欧的影响知乎 编辑:程序博客网 时间:2024/05/18 01:14

参考资料:gityuan的知乎回答,http://gityuan.com,weibo.com/gityuan(微博)

1.基础知识

1.android系统不能在子线程中更新UI;因为系统的UI控件不是线程安全的,如果使用加锁使其线程安全,则会让UI控件变得复杂和低效,并可能阻塞某些进程的执行。

2.ThreadLocal类用来提供线程内部的局部变量。这些变量在多线程环境下访问(通过get或set方法访问)时能保证各个线程里的变量相对独立于其他线程内的变量,ThreadLocal实例通常来说都是private static类型。

3.一个线程中只有一个Looper实例和一个MessageQueue实例,可以有多个handler对象。

2.Looper笔记

一般先调用Looper.prepare,再调用Looper.loop()方法

Looper.prepare()方法中,根据sThreadLocal.get()是否为空,为空时才调用sThreadLocal.set(new Looper(quitAllowed)),不为空则抛出异常,从而保证了一个线程中只有一个Looper。

private static void prepare(booleanquitAllowed) {  if (sThreadLocal.get() != null) {    throw new RuntimeException("Only oneLooper may be created per thread");  }  sThreadLocal.set(new Looper(quitAllowed));}

Looper的构造函数中新建了MessageQueue对象,每个线程中都有一个MessageQueue对象:

private Looper(boolean quitAllowed) {   mQueue = new MessageQueue(quitAllowed);   mThread = Thread.currentThread();}

通过myLooper()方法可获得当前线程的looper实例:

public static Looper myLooper() {  return sThreadLocal.get();}

Looper中有static对象sMainLooper,可通过static方法getMainLooper()来获得主线程的looper实例。

3.Handler笔记

Handler的构造函数,把handler和looper关联起来:

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

handler的dispatchMessage()方法中分发message:

public void dispatchMessage(Message msg) {  if (msg.callback != null) {    handleCallback(msg);  } else {    if (mCallback != null) {      if (mCallback.handleMessage(msg)) {      return;      }    }    handleMessage(msg);  }}
handler.handleMessage(),一般需重写该方法来处理消息

post(Runnable r)方法也是通过sendMessage实现的,post()会将该runable放入message,并把message的callback指向该runnable,并通过handleCallback最终运行该可执行代码:

private static Message getPostMessage(Runnable r) {  Message m = Message.obtain();  m.callback = r;  return m;}private static void handleCallback(Message message) {  message.callback.run();}

4.MessageQueue笔记

MessageQueue中的mMessages指向队头的message,对于一个新的message,会在enqueueMessage()方法中,根据msg.when等信息,将该message插入到适当的位置:

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("MessageQueue", 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;    }
MessageQueue的next()方法会进入一个死循环,返回一下个要处理的message。

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 (false) Log.v("MessageQueue", "Returning message: " + msg);                        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("MessageQueue", "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;        }    }

5.发送message的过程

handler.sendMessage()——hanler.enqueueMessage()——queue.enqueueMessage()

private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {  //把将要发送的message.target指向自己  msg.target = this;  if (mAsynchronous) {    msg.setAsynchronous(true);  }  return queue.enqueueMessage(msg, uptimeMillis);}

6.处理message的过程

Looper.loop()——queue.next()——msg.target.dispatchMessage()

Looper.loop()代码如下:

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;        // Make sure the identity of this thread is that of the local process,        // and keep track of what that identity token actually is.        Binder.clearCallingIdentity();        final long ident = Binder.clearCallingIdentity();        for (;;) {            Message msg = queue.next(); // might block            if (msg == null) {                // No message indicates that the message queue is quitting.                return;            }            // This must be in a local variable, in case a UI event sets the logger            Printer logging = me.mLogging;            if (logging != null) {                logging.println(">>>>> Dispatching to " + msg.target + " " +                        msg.callback + ": " + msg.what);            }            msg.target.dispatchMessage(msg);            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();        }    }

7.主线程的消息机制

ActivityThread实际上并非线程,并没有真正继承Thread类,只是往往运行在主线程,承载ActivityThread的主线程是由Zygote fork而创建的进程。

ActivityThread的main()代码如下:

public static void main(String[] args) {        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");        SamplingProfilerIntegration.start();        // CloseGuard defaults to true and can be quite spammy.  We        // disable it here, but selectively enable it later (via        // StrictMode) on debug builds, but using DropBox, not logs.        CloseGuard.setEnabled(false);        Environment.initForCurrentUser();        // Set the reporter for event logging in libcore        EventLogger.setReporter(new EventLoggingReporter());        AndroidKeyStoreProvider.install();        // Make sure TrustedCertificateStore looks in the right place for CA certificates        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());        TrustedCertificateStore.setDefaultUserDirectory(configDir);        Process.setArgV0("<pre-initialized>");        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"));        }        // End of event ActivityThreadMain.        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);        Looper.loop();        throw new RuntimeException("Main thread loop unexpectedly exited");    }

其中:

main()方法中调用了prepareMainLooper(),所以主线程中可以直接新建handler,而不用先调用prepare()方法;此外,ActivityThread中有一个内部类Activity.H(继承自handler)的对象mH,用来处理Activity生命周期相关的message。

thread.attach(false)会创建一个Binder线程(具体是指ApplicationThread,Binder的服务端,用于接收系统服务ApplicationManagerService发送来的事件),该Binder线程通过Activity.H将Message发送给主线程。


Looper.loop()方法会循环读取主线程的MessageQueue中的message,当MessageQueue中没有message时,message.next()方法会发生阻塞(通过nativePollOnce()方法),此时主线程会释放CPU资源进入休眠状态,直到下个消息到达或者有事务发生,通过往pipe管道写端写入数据来唤醒主线程工作。

当有新的事件发生时,系统进程会通过binder方式调用ApplicationThreadd的对应方法(比如启动服务时调用scheduleCreateService()方法),在该方法内调用了sendMessage()方法,通过mH对象sendMessage()向主线程的消息队列中发送了消息,进而唤醒了主线程(MessageQueue的enqueueMessage()方法会调用nativeWake(mPtr)方法进行唤醒)。

public final void scheduleCreateService(IBinder token, ServiceInfo info, CompatibilityInfo compatInfo, int processState) {            updateProcessState(processState, false);            CreateServiceData s = new CreateServiceData();            s.token = token;            s.info = info;            s.compatInfo = compatInfo;            sendMessage(H.CREATE_SERVICE, s);        }private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {        if (DEBUG_MESSAGES) Slog.v(            TAG, "SCHEDULE " + what + " " + mH.codeToString(what)            + ": " + arg1 + " / " + obj);        Message msg = Message.obtain();        msg.what = what;        msg.obj = obj;        msg.arg1 = arg1;        msg.arg2 = arg2;        if (async) {            msg.setAsynchronous(true);        }        mH.sendMessage(msg);    }




原创粉丝点击