Android消息机制学习小结

2018-01-31  本文已影响12人  r09er

Android中的消息机制

在Android中,只能在UI线程对控件进行操作,只能在子线程进行耗时操作,例如IO和网络请求,所以需要一个消息通知方式,让耗时操作结束后,主线程能够及时响应.这个机制就是Android中的消息机制.
Android的消息机制主要是指Handler的运行机制以及Handler所附带的MessageQueue和Looper的工作过程.

示例图

图1-1 示例图
Handler基本使用,在子线程断续休眠2S,通过handler向主线程发送消息通知UI刷新,通过查看log和界面就能观察到变化
  private static final String TAG = HandlerTestActivity.class.getSimpleName();
    private Handler handler;

    private ExecutorService executorService;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        executorService = Executors.newCachedThreadPool();
        final TextView tvMsg = findViewById(R.id.tv_msg);

        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        String s = msg.getData().getString("msg");
                                tvMsg.setText("Content:  " + s);
                        Log.d(TAG, "handleMessage: "+s+Thread.currentThread());
                        break;
                    default:
                        break;
                }
                return false;
            }
        });

    }

    public void sendMessage(View view) {
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                //other thread
                
                int i = 0;
                try {
                    while (i < 5) {
                        TimeUnit.SECONDS.sleep(2);
                        Message message = new Message();
                        message.what = 1;
                        Bundle bundle = new Bundle();
                        bundle.putString("msg", "" + i);

                        message.setData(bundle);
                        handler.sendMessage(message);
                        i++;
                        Log.d(TAG, "run: "+Thread.currentThread());
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
    }

1消息队列的工作原理

消息队列在Android中指的是MessageQueue,在MessageQueue中主要包含两个操作:插入和读取,在读取的过程中,会伴随着删除的操作,插入和读取对应的方法分别是enqueueMessage和next.尽管叫做消息队列,但是内部的数据结构是单链表,而不是队列,因为单链表在插入和删除的性能较好.
在MessageQueue方法中,enqueueMessage方法只是一个的链表插入操作.但是next方法是一个无限循环,如果队列中没有消息,就会一直阻塞,当有新的消息来时,next方法就会返回这条消息,并从链表中删除.

 Message next() {
...
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;
                }
}

....
}
2Looper的工作原理

Looper在消息机制中扮演着消息循环的角色,会不停地从MessageQueue中查看是否有新消息,如果有新消息,就会马上进行处理,否则也会一直阻塞.在Looper的构造方法中,会构造一个新的MessageQueue,通过ThrealLocal来保证每一个线程有且只有一个Looper

  public static void prepare() {
        prepare(true);
    }

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

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

Handler的工作需要Looper,在没有Looper的线程使用Handler发送消息,就会抛出一个运行时异常.

No Looper; Looper.prepare() wasn't called on this thread.

在主线程中我们没有主动调用Looper.prepare也能够正常使用Handler是因为在应用启动的时候,系统已经在ActivityThread的main方法中主动为我们调用了一个Looper.prepare(),因为四大组件的注册和使用都需要handler的支持.

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

Looper.prepareMainLooper();
...
}

在prepareMainLooper方法的注释上就为标明了这一点,


图2-1 prepareMainLooper.png

在子线程中创建了一个Looper,需要在使用结束的时候通过Looper的quit或者quitSafely方法终止消息循环,否则这个线程会一直处于等待状态,如果调用了quit方法,这个线程就会自动终止.

Looper还有一个很重要的loop方法,只有调用了loop之后,消息循环才会真正起作用,在loop中,当Message不为空,就会调用到msg持有的handler对象的dispatchMessage方法,Handler中的dispatchMessage方法是在创建Handler时所使用的Looper中执行,所以就可以将方法回调到主线程中.

所以在UI线程创建Handler,那么dispatchMessage就会在UI线程被调用,最终会调用的到handler的handleMessage方法.

 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
            final Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

            final long traceTag = me.mTraceTag;
            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }
            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();
        }
    }

在loop方法中,也是一个死循环,不断从MessageQueue调用next方法获取Message,直到Message为空,才跳出循环.当Looper的quit方法被调用时,会调用MessageQueue的quit方法,将消息队列标记为退出状态,next方法就会返回null.由于MessageQueue的next方法是阻塞方法,当没有消息时会一直阻塞,也就导致了looper的loop方法阻塞,所以必须对用Looper的quit方法.

3. Handler工作原理

Handler的工作主要包含消息的发送和接收过程.消息的发送可以通过各种post方法,和各种send方法实现,post方法最终调用的也是send.所以主要看sendMessage方法就行.

public final boolean sendMessage(Message msg){
        return sendMessageDelayed(msg, 0);
    }
 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);
    }

通过源码可以发现,无论handler通过什么方式发送一条消息,最终都是将这条消息插入到MessageQueue的链表中,MessageQueue的next会返回这条消息给Looper,Looper收到消息之后进行处理,最终由Looper交给Hanlder的dispatchMessage进行消息接收处理,这样Handler就进入到消息处理的阶段.

4.消息处理

消息处理是在Handler的dispatchMessage中执行

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

在dispatchMessage方法中可以看到,会先判断Message的callback方法是否为空,Message的callback实际上是一个Runnable对象,就是通过handler.post(Runnable r)的Runnable对象.在第二个判断中mCallback对象是构造Handler时传入的Callback接口对象,通过这种方式创建的Handler就不需要继承Handler

Handler handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                return false;
            }
        });

dispatchMessage根据不同的handler创建方式最终回调到各个的handleMessage方法,
Handler发送和处理消息的过程基本就是这样.

上一篇 下一篇

猜你喜欢

热点阅读