欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Handler 使用

程序员文章站 2022-07-14 17:06:12
...

Handler 使用

一、Handler和Looper关联

1、子线程内先调用Looper.prepare();
2、再创建Handler,
3、Looper.loop(); 让Looper开始工作

二、Looper

Looper创建

一个线程只能创建一个Looper,且把Looper 存到ThreadLocal中;

    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构造函数创建MassageQueue;

//Looper 关联主线程时为false   
private Looper(boolean quitAllowed) {
        mQueue = new MessageQueue(quitAllowed);
        mThread = Thread.currentThread();
    }

Handler构造函数会关联Looper

public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                    (klass.getModifiers() & Modifier.STATIC) == 0) {
                Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                    klass.getCanonicalName());
            }
        }

        mLooper = Looper.myLooper();
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

其中mLooper = Looper.myLooper();获取本线程ThreadLocal中的Looper

/**
     * Return the Looper object associated with the current thread.  Returns
     * null if the calling thread is not associated with a Looper.
     */
    public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

Looper.loop是个死循环;

不断从消息队列中读取消息,取出消息进行分发;但阻塞是在queue.next();
退出条件-msg=null(MessageQueue 返回空);

/**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the 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;
        ..........................
        for (;;) {
            Message msg = queue.next(); // might block
            //退出时,获取消息为null
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }

           ..........................
            try {
            //分发消息--【Handler target】;
                msg.target.dispatchMessage(msg);
                dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
            } finally {
                if (traceTag != 0) {
                    Trace.traceEnd(traceTag);
                }
            }
            
        }
    }

同步障碍器

作用:屏蔽后面同步消息,后面的异步消息会执行

queue.next(),是个死循环,直到取到一个消息;

闲置任务

执行完所有消息后会执行闲置Handler;没有闲置任务则进入阻塞状态。

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();
            }
            //nextPollTimeoutMillis 为0立即返回,为-1,永久等待(需要主动唤醒);
            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) {//判断当前队首的消息是否是同步障碍器(target=nul,msg !=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.
                //执行完所有消息或执行闲置Handler任务
                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.
            //执行闲置Handler
            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;
        }
    }

Message enqueueMessage 函数,往队列中插入消息,按时间执行顺序插入,链表头是距离执行时间最短的消息;

boolean enqueueMessage(Message msg, long when) {
       ..............
        synchronized (this) {
            if (mQuitting) {
               ..............
                return false;
            }

            msg.markInUse();
            msg.when = when;
            Message p = mMessages;
            boolean needWake;
          //队列首部为null /入队消息需要马上执行/入队消息早于队首消息,线程已阻塞,需要唤醒
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;//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()) {//队列是阻塞,且插入异步消息执行时间更晚(否则上面会break),因此不需要唤醒。
                        needWake = false;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
          //唤醒消息队列( nativePollOnce处进入的睡眠)
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }

调用Looper的退出,quit()里面,调用消息队列推出;

 public void quit() {
        mQueue.quit(false);
    }
    
 public void quitSafely() {
        mQueue.quit(true);
    }

消息推队列退出

   void quit(boolean safe) {
        if (!mQuitAllowed) {
            throw new IllegalStateException("Main thread not allowed to quit.");
        }

        synchronized (this) {
            if (mQuitting) {
                return;
            }
            mQuitting = true;

            if (safe) {
                removeAllFutureMessagesLocked();
            } else {
                removeAllMessagesLocked();
            }

            // We can assume mPtr != 0 because mQuitting was previously false.
            nativeWake(mPtr);
        }
    }
相关标签: java android