Handler(上)那些事儿

Handler概述

Activity是不能进行耗时操作的,否则会出现ANR无响应,所以如果要进行耗时操作,必须开启子线程去执行耗时操作.那么问题来了,UI数据的变化必须在主线程里实现,子线程是不允许进行UI操作的,这个时候就需要Handler去实现子线程和主线程的通信,所以Handler机制是Android中非常重要的消息通讯机制.所以理解了解学习Handler是非常必要的.

ThreadLocal

这里Handler的基本使用就不再做过多的讲解.为了更好的理解Handler,ThreadLocal作为知识储备是很有必要学习的,因为在后面的分析中需要和他见面.

ThreadLocal是用来线程间数据的存储的.怎么理解?我们来看看下面一段代码

    ThreadLocal<String> threadLocal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        threadLocal = new ThreadLocal<>();
        threadLocal.set("Main");

        new Thread(){
            @Override
            public void run() {
                super.run();
                System.out.println("thread "+threadLocal.get());// thread null
            }
        }.start();

我们定义了一个存储String的ThreadLocal,在主线程去添加一个Main字符串,接着开启一个子线程去获取,最终输出是 thread null,并没有我们所想的 thread Main.这就体现了线程进的数据存储,具体咱们实现的咱们来看看关键的get 和 set方法.

set

    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

我们可以看到我们主要是将数据存储到ThreadLocalMap中,以当前线程为key,将value存储起来,这也就为什么主线程里set的数据,子线程get不到.因为一个是以主线程为key去获取数据,一个是以子线程为key去获取数据,当然获取不到数据.

get

    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

get方法也一样,通过当前线程为key.拥有的知识储备接下来,我们来看看消息队列的原理.

MessageQueue

我们在使用Handler的时候,传递的消息就是Message,那么这些Message就是添加到MessageQueue队列中,依次去发送数据的.所以MessageQueue的主要作用就是接管理Message的队列,MessageQueue主要是两个方法enqueueMessage(插入)和next(读入).我们来仔细看看

enqueueMessage

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

上诉代码,我们需要知道四点

  • msg.target就是handler,就是去处理发来message的handler(可以看Message的源码里的target)
  • enqueueMessage第二个参数表示执行的时间,是毫秒为单位
  • Message是以单链表的形式进行,通过执行的时间去排列插入.
  • Message.when就是来保存索要执行的时间

这里我不会对该段代码详细讲解.文章前半段想让读者有大概的了解,知道消息机制经历那些过程即可,在文章的后半段会在继续深入讲解.

next

    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;
        (1) 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) {
        (2) 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;
        }
    }

重点来看看(1) (2)处的代码

  1. 从该处代码可以看出,消息的读取其实是死循环一直读取的.那么就抛出一个问题,为什么这样一直的死循环,app不会卡死?这么消耗资源为什么app还是很流程? 该问题留到后面 哈哈
  2. 还记得enqueueMessage方法分析的第四点,message.when表示的是Message索要执行的时间,所以该出代码就是通过when来判断是否执行该message,没有着记录下还需要等待的时间,可以执行则返回该message.

next方法主要是一个无线循环的方法,循环的从独处链表中的Message,并且返回.

Looper的工作原理

Looper的主要作用就是负责绑定当前线程,使消息循环起来.

我们知道,Handler的工作需要Looper,没有Looper的线程会报错,那么如何为一个线程创建Looper呢?其实很简单,通过Looper#prepare方法,为当前线程创建一个Looper,在通过Looper#loop方法去开启消息循环.那么我们来看看方法的源码.

构造方法

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

我们看到,在构造方法中,Looper回去初始化MessageQueue,并且获取当前线程的线程.

prepare

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

我们可以看到,prepare方法通过ThreadLocal,将当前线程和Looper相绑定.

myLooper

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

获取当前线程所绑定的Looper对象.

loop


    public static void loop() {
      (1)  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();

        // Allow overriding a threshold with a system prop. e.g.
        // adb shell 'setprop log.looper.1000.main.slow 1 && stop && start'
        final int thresholdOverride =
                SystemProperties.getInt("log.looper."
                        + Process.myUid() + "."
                        + Thread.currentThread().getName()
                        + ".slow", 0);

        boolean slowDeliveryDetected = false;

     (2)for (;;) {
          (3)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 traceTag = me.mTraceTag;
            long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;
            long slowDeliveryThresholdMs = me.mSlowDeliveryThresholdMs;
            if (thresholdOverride > 0) {
                slowDispatchThresholdMs = thresholdOverride;
                slowDeliveryThresholdMs = thresholdOverride;
            }
            final boolean logSlowDelivery = (slowDeliveryThresholdMs > 0) && (msg.when > 0);
            final boolean logSlowDispatch = (slowDispatchThresholdMs > 0);

            final boolean needStartTime = logSlowDelivery || logSlowDispatch;
            final boolean needEndTime = logSlowDispatch;

            if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
                Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
            }

            final long dispatchStart = needStartTime ? SystemClock.uptimeMillis() : 0;
            final long dispatchEnd;
            try {
           (4)   msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            if (logSlowDelivery) {
                if (slowDeliveryDetected) {
                    if ((dispatchStart - msg.when) <= 10) {
                        Slog.w(TAG, "Drained");
                        slowDeliveryDetected = false;
                    }
                } else {
                    if (showSlowLog(slowDeliveryThresholdMs, msg.when, dispatchStart, "delivery",
                            msg)) {
                        // Once we write a slow delivery log, suppress until the queue drains.
                        slowDeliveryDetected = true;
                    }
                }
            }
            if (logSlowDispatch) {
                showSlowLog(slowDispatchThresholdMs, dispatchStart, dispatchEnd, "dispatch", 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();
        }
    }

上诉代码主要看这四个关键点

  1. loop方法,主要操作逻辑的对象是与当前线程想绑定的Looper对象.
  2. loop方法里有一个死循环,大部分的业务逻辑都在这个死循环里
  3. 这个循环里,不断循环的调用MessageQueue#next方法,去拿到将要去分发的message事件.
  4. 通过message.target也就是handler,的dispatchMessage方法去回调对应的message方法,从而可以去处理该message.

局部总结

现在我们可以大致的总结一下,Message MessageQueue Looper ThreadLocal 四者的关系.

  • Message是消息的载体,表示将要分发的消息的内容;
  • MessageQueue则是用于管理消息的载体message,通过enqueueMessage方法将新Message添加到队列中,next用于从队列中取出将要执行的Message;
  • Looper则消息队列的驱使着,通过ThreadLocal将线程和Looper绑定,通过loop方法不断的调用messageQueue#next方法去获取将要执行的Message,通过Handler#dispatchMessage回调去操作.

那么部分人在平时的使用中可能连Looper都没有用到,单纯一个Handler就够,那么我们还需要来看看Handler的源码来一探究竟.

来看看下一遍Handler(下)那些事儿

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值