2018-11-14

Android Handler消息处理机制

我们知道activity的异常响应事件为5秒,也就是说.超过该时间就会报ANR(Application Not Response)异常,所以耗时操作就不能在主线程中进行,需要放入到子线程中。而当异步处理成功后需要更新视图,但子线程中不能更新UI,所以这个时候就需要借助handler来处理。
即handler在新线程中发送消息,在主线程中接收并处理消息。

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //发送消息
                Message message=Message.obtain();
                message.what=0x001;
                myHandler.sendMessage(message);
            }
        }).start();
    }

    @SuppressLint("HandlerLeak")
    private Handler myHandler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //接受消息,并处理消息
            switch (msg.what){
                case 0x001:
                    break;
            }
        }
    };

Handler作用

①在新线程中发送消息
②在主线程中获取和处理消息
Handler中用来发送和处理消息的方法:
★ void handleMessage(Message msg):处理消息的方法。通常用于被重写。
★ final boolean hasMessages(int what):检查消息队列中是否包含what属性指定值的消息。
★ final boolean hasMessages(int what,Object object):检查消息队列中是否包含what属性为指定值且object属性为指定消息对象的消息。
★ 多个重载的Message obtainMessage():获取消息。
★ sendEmptyMessage(int what):发送空消息。
★ final boolean sendEmptyMessageDelayed(int what,long delayMillis):指定多少毫秒后发送空消息。
★ final boolean sendMessage(Message msg):立即发送消息。
★final boolean sendMessageDelayed(Message msg,long delayMillis):指定多少毫秒后发送消息。
③handler作用
程序使用handler发送消息,而handler发送的消息被送到了指定的MessageQueue中。而MessageQueue被Looper管理,Looper循环的去读取MessageQueue中的Message,并把消息分发给对应的handler进行处理。

MessageQueue

消息队列,采用先进先出的方式去管理Message。在程序创建Looper对象时,会在它的构造中创建MessageQueue对象

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

MessageQueue中有两个重要的方法,一个是 enqueueMessage(Message msg, long when)即入队方法,next()即出队。

Looper

通过查看Looper源码我们知道在Looper的构造中创建了MessageQueue,而Looper又是怎么被创建的呢?

Looper创建方法

①UI线程
在主线程中,系统已经初始化了一个Looper对象,所有程序只需要创建Handler对象即可,然后就可以通过Handler发送消息,处理消息。
②子线程
必须自己创建一个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中的loop()方法

loop()方法使用一个死循环不断的去读取MessageQueue中的消息,并将取出消息发送给该消息对应的handler去处理。

        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方法返回null,当Looper退出后,Handler就无法发送消息,send出去的消息会返回false;所以当我们在子线程中创建了Looper并且所有的消息都处理完毕的时候,要记得调用Looper的quit 方法,否则子线程就一直处于等待状态。

总结

★ Looper:每一个线程只有一个Looper,它负责管理MessageQueues,不断的从MessageQueue中读取消息,在把读取到的消息发送给对应的Handler处理。
★ MessageQueue:由Looper管理,采用先进先出的方式管理Message。
★ Handler:把消息发送给Looper管理的MessageQueue,并负责处理Looper分发给它的消息。

你可能感兴趣的:(2018-11-14)