从Android源码角度,深度分析Handler机制

Android Handler消息机制:sendMessage与sendToTarget对比分析 在Android开发中,消息机制是实现线程间通信的核心技术,主要由Handler、Looper和Message构成。其底层原理基于生产者-消费者模型,通过消息队列实现异步处理。从技术实现来看,Handler既负责消息发送也处理消息,而Message作为数据载体,通过复用机制(Message.obtain())优化内存使用。sendMessage和sendToTarget是两种典型的消息发送方式,前者更灵活支持动态路由,后者通过提前绑定Handler提升性能。在UI更新、动画渲染等高频率消息场景中,合理选择发 阅读详情

Handler作为Android开发中,线程间通信的常用方案,其内部的机制原理到底是怎样的呢?我们这篇文章,来一探究竟。

一、情景分析:

一般来说,当我们需要执行耗时操作,此时我们开启工作线程,当我们完成耗时操作之后,我们需要同步主线程,也就是UI线程,进行刷新。此时我们可以考虑使用Handler。

当然了,也可以主线程同步子线程使用Handler,不过一般比较常用的上面所说的场景。

二、主角登场:

Message、Handler、MessageQueue、Looper

先用一句话把这四个要素串联起来:

在工作线程中完成耗时操作后,将我们需要传递给主线程的数据,用Message包装起来,然后通过Handler作为信使发送Message到MessageQueue消息队列。另一边,主线程的Looper会不断循环地从MessageQueue中取Message,当取到Message之后,会将该Message分发给对应的Handler进行处理。

三、Message:

位于:

package android.os;

构造方法:

    /** Constructor (but the preferred way to get a Message is to call {@link #obtain() Message.obtain()}).
    */
    public Message() {
    }

obtain方法:

    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain()

    /**
     * Same as {@link #obtain()}, but copies the values of an existing
     * message (including its target) into the new one.
     * @param orig Original message to copy.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Message orig)

    /**
     * Same as {@link #obtain()}, but sets the value for the <em>target</em> member on the Message returned.
     * @param h  Handler to assign to the returned Message object's <em>target</em> member.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h)

    /**
     * Same as {@link #obtain(Handler)}, but assigns a callback Runnable on
     * the Message that is returned.
     * @param h  Handler to assign to the returned Message object's <em>target</em> member.
     * @param callback Runnable that will execute when the message is handled.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h, Runnable callback)

    /**
     * Same as {@link #obtain()}, but sets the values for both <em>target</em> and
     * <em>what</em> members on the Message.
     * @param h  Value to assign to the <em>target</em> member.
     * @param what  Value to assign to the <em>what</em> member.
     * @return A Message object from the global pool.
     */
    public static Message obtain(Handler h, int what)

    /**
     * Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>, and <em>obj</em>
     * members.
     * @param h  The <em>target</em> value to set.
     * @param what  The <em>what</em> value to set.
     * @param obj  The <em>object</em> method to set.
     * @return  A Message object from the global pool.
     */
    public static Message obtain(Handler h, int what, Object obj)

    /**
     * Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>,
     * <em>arg1</em>, and <em>arg2</em> members.
     *
     * @param h  The <em>target</em> value to set.
     * @param what  The <em>what</em> value to set.
     * @param arg1  The <em>arg1</em> value to set.
     * @param arg2  The <em>arg2</em> value to set.
     * @return  A Message object from the global pool.
     */
    public static Message obtain(Handler h, int what, int arg1, int arg2)

    /**
     * Same as {@link #obtain()}, but sets the values of the <em>target</em>, <em>what</em>,
     * <em>arg1</em>, <em>arg2</em>, and <em>obj</em> members.
     *
     * @param h  The <em>target</em> value to set.
     * @param what  The <em>what</em> value to set.
     * @param arg1  The <em>arg1</em> value to set.
     * @param arg2  The <em>arg2</em> value to set.
     * @param obj  The <em>obj</em> value to set.
     * @return  A Message object from the global pool.
     */
    public static Message obtain(Handler h, int what,
            int arg1, int arg2, Object obj)

源码中,这些obtain方法中,都是调用了下面的obtain方法:

    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

    public static final Object sPoolSync = new Object();
    private static Message sPool;

解析如下:

sPoolSync是一个同步锁对象

sPool是一个全局池消息实例

这个方法其实就是,从全局池返回一个消息实例,这样子我们在很多情况下可以避免分配新对象。 

因此,使用obtain方法,在大多数情况下,可以避免消耗更多的内存资源。

Message的三个重要的包间成员变量:

    /*package*/ Handler target;

    /*package*/ Runnable callback;

    // sometimes we store linked lists of these things
    /*package*/ Message next;

Message的四个公开的变量what、arg1、arg2、obj,这些一般是用来存储消息进行传递。 

四、Handler:

位于:

package android.os;

构造方法:

    /**
     * Default constructor associates this handler with the {@link Looper} for the
     * current thread.
     *
     * If this thread does not have a looper, this handler won't be able to receive messages
     * so an exception is thrown.
     *
     * @deprecated Implicitly choosing a Looper during Handler construction can lead to bugs
     *   where operations are silently lost (if the Handler is not expecting new tasks and quits),
     *   crashes (if a handler is sometimes created on a thread without a Looper active), or race
     *   conditions, where the thread a handler is associated with is not what the author
     *   anticipated. Instead, use an {@link java.util.concurrent.Executor} or specify the Looper
     *   explicitly, using {@link Looper#getMainLooper}, {link android.view.View#getHandler}, or
     *   similar. If the implicit thread local behavior is required for compatibility, use
     *   {@code new Handler(Looper.myLooper())} to make it clear to readers.
     *
     */
    @Deprecated
    public Handler() {
        this(null, false);
    }
    @Deprecated
    public Handler(@Nullable Callback callback) {
        this(callback, false);
    }

    public Handler(@NonNull Looper looper) {
        this(looper, null, false);
    }

    public Handler(@NonNull Looper looper, @Nullable Callback callback) {
        this(looper, callback, false);
    }

    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
    public Handler(boolean async) {
        this(null, async);
    }
    /**
     * Use the {@link Looper} for the current thread with the specified callback interface
     * and set whether the handler should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by {@link MessageQueue#enqueueSyncBarrier(long)}.
     *
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    public Handler(@Nullable 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();  //返回与当前线程关联的Looper对象
        if (mLooper == null) {
            throw new RuntimeException(
                "Can't create handler inside thread " + Thread.currentThread()
                        + " that has not called Looper.prepare()");
        }
        mQueue = mLooper.mQueue;  //返回Looper对象的消息队列
        mCallback = callback;
        mAsynchronous = async;
    }

    /**
     * Use the provided {@link Looper} instead of the default one and take a callback
     * interface in which to handle messages.  Also set whether the handler
     * should be asynchronous.
     *
     * Handlers are synchronous by default unless this constructor is used to make
     * one that is strictly asynchronous.
     *
     * Asynchronous messages represent interrupts or events that do not require global ordering
     * with respect to synchronous messages.  Asynchronous messages are not subject to
     * the synchronization barriers introduced by conditions such as display vsync.
     *
     * @param looper The looper, must not be null.
     * @param callback The callback interface in which to handle messages, or null.
     * @param async If true, the handler calls {@link Message#setAsynchronous(boolean)} for
     * each {@link Message} that is sent to it or {@link Runnable} that is posted to it.
     *
     * @hide
     */
    @UnsupportedAppUsage
    public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

总结下创建Handler实例的时候,主要做了以下事情:

1、获取当前Handler实例所在线程的Looper对象。

2、如果Looper不为空,则获取Looper的消息队列,并赋值给Handler的成员变量mQueue。

3、可以设置Callback来处理消息回调。

Handler是进行消息处理,但是处理消息的不是它,真正来处理消息的是Looper。

流程:Handler发送消息,然后排队等待,等Looper处理消息,Looper处理完消息通知Handler来领取消息,Handler领取到消息后进行分发处理。

总结出两条结论:

1、Handler有且只能绑定一个线程的Looper。

2、Handler将消息发送给Looper的消息队列MessageQueue,等待处理。

sendMessage方法:

sendEmptyMessage--->sendEmptyMessageDelayed--->sendMessageDelayed

sendMessage--->sendMessageDelayed

sendMessageDelayed--->sendMessageAtTime

sendEmptyMessageAtTime--->sendMessageAtTime

sendMessageAtTime--->enqueueMessage

    /**
     * Enqueue a message into the message queue after all pending messages
     * before the absolute time (in milliseconds) <var>uptimeMillis</var>.
     * <b>The time-base is {@link android.os.SystemClock#uptimeMillis}.</b>
     * Time spent in deep sleep will add an additional delay to execution.
     * You will receive it in {@link #handleMessage}, in the thread attached
     * to this handler.
     * 
     * @param uptimeMillis The absolute time at which the message should be
     *         delivered, using the
     *         {@link android.os.SystemClock#uptimeMillis} time-base.
     *         
     * @return Returns true if the message was successfully placed in to the 
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the message will be processed -- if
     *         the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     */
    public boolean sendMessageAtTime(@NonNull 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(@NonNull MessageQueue queue, @NonNull Message msg,
            long uptimeMillis) {
        msg.target = this;
        msg.workSourceUid = ThreadLocalWorkSource.getUid();

        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }

    boolean enqueueMessage(Message msg, long when) {
        //判断msg的所属Handler
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

        //因为是队列,有先后之分,因此使用了同步机制
        synchronized (this) {
            if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
            }

            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
            Message p = mMessages;
            boolean needWake;
            //如果队列为空,或者等待时间为0,或者比前面的Message的等待时间要短,就插队
            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循环是为了取出一个空的或者when比当前message长的一个消息,然后进行插入
                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;
    }

dispatchMessage方法:

    /**
     * Handle system messages here.
     */
    public void dispatchMessage(@NonNull Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            handleMessage(msg);
        }
    }
    /**
     * Subclasses must implement this to receive messages.
     */
    public void handleMessage(@NonNull Message msg) {
    }

五、MessageQueue:

package android.os;

enqueueMessage方法:

    boolean enqueueMessage(Message msg, long when) {
        //判断msg的所属Handler
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }

        //因为是队列,有先后之分,因此使用了同步机制
        synchronized (this) {
            if (msg.isInUse()) {
                throw new IllegalStateException(msg + " This message is already in use.");
            }

            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
            Message p = mMessages;
            boolean needWake;
            //如果队列为空,或者等待时间为0,或者比前面的Message的等待时间要短,就插队
            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循环是为了取出一个空的或者when比当前message长的一个消息,然后进行插入
                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;
    }

next方法:

    @UnsupportedAppUsage
    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进入阻塞状态,此时线程会释放CPU资源进入休眠状态
            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;
                }

                // Process the quit message now that all pending messages have been handled.
                //外部调用quit命令,跳出循坏
                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;
        }
    }

 MessageQueue是一个数据结构,一般我们叫它消息队列,但是其实它不是一个队列,它的数据结构是单向链表。 它的作用就是存储Message,消息进入MessageQueue,然后又从MessageQueue中被取出来。

六、Looper: 

package android.os;

Looper是循坏处理消息的发动机,它不断从消息队列中取出的消息,处理,然后分发处理事件。

每个线程有且仅有一个Looper。

loop方法:

    /**
     * Run the message queue in this thread. Be sure to call
     * {@link #quit()} to end the loop.
     */
    public static void loop() {
        //获取当前的Looper
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //获取当前Looper的消息队列
        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;

        for (;;) {
            //取出队头的消息
            Message msg = queue.next(); // might block
            //如果消息为空,则直接return
            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 {
                //调用消息的对应的Handler的dispatchMessage方法
                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、我们new了一个Handler,然后我们通过handler.sendMessage发送消息,然后我们在handler的handleMessage方法中拿到消息并处理。

------这到底是怎么做到的?

2、为什么在主线程中可以直接new Handler并实现线程通信,而在子线程中不行?

 ActivityThread的部分源码:

    public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");

        // Install selective syscall interception
        AndroidOs.install();

        // 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();

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        // Call per-process mainline module initialization.
        initializeMainlineModules();

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

        // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
        // It will be in the format "seq=114"
        long startSeq = 0;
        if (args != null) {
            for (int i = args.length - 1; i >= 0; --i) {
                if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
                    startSeq = Long.parseLong(
                            args[i].substring(PROC_START_SEQ_IDENT.length()));
                }
            }
        }
        ActivityThread thread = new ActivityThread();
        thread.attach(false, startSeq);

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

3、既然一个线程因为Looper.loop变成了永动机,那为什么不会出现ANR呢? 

------拿主线程举例,主线程本身也是一个线程,线程是有生命周期的,任务执行结束,或者在执行任务过程中抛出了异常,线程就结束了。恰恰正是由于Looper维护的这个死循环才能保证主线程不退出。

ANR是由于在主线程执行耗时操作在规定时间没没有完成,触发了Android系统的ANR机制。这个与Looper维护的死循环没有任何关系。

当然loop也不是一直在循环处理任务,如果没有任务,线程会休眠。

4、一个线程可以有几个Handler,一个线程可以有几个Looper,一个Hanlder可以对应几个Looper?

--- ThreadLocal:

ThreadLocal和Synchronized都是为了解决多线程中相同变量的访问冲突问题,不同的点是:

Synchronized是通过线程等待,牺牲时间来解决访问冲突。

ThreadLocal是通过每个线程单独一份存储空间,牺牲空间来解决冲突,并且相比Synchronized,ThreadLocal具有线程隔离的效果,只有在线程内才能获取到对应的值,线程外不能访问到想要的值。

5、Handler会造成内存泄漏吗?为什么会?怎么解决?

--- 非静态内部类,或者匿名内部类。使得Handler默认持有外部类的引用。因此在Activity销毁时,由于Handler可能有未执行完/正在执行的Message。导致Handler持有Activity的引用。进而导致GC无法回收Activity,从而产生了内存泄漏。

--- Activity销毁的时候,也就是在回调onDestroy生命周期方法的时候,清空Handler中未执行完或正在执行的Callback以及Message。

--- Handler的内存泄漏是可能会出现,并且它不是会一直泄漏。

 

Android校招笔试题解析:从Handler到Binder,掌握核心机制与性能优化 在Android应用开发中,消息循环、跨进程通信和视图分发是构建稳定应用的基础。理解Handler与Looper的工作机制,掌握Binder的IPC原理,以及熟悉Activity启动流程和View事件分发,是校招笔试的高频考点。同时,内存泄漏、GC回收、线程池并发和Bitmap图片加载等性能优化问题,直接体现了工程师的工程实践能力。本文围绕一套Android校招笔试题,梳理其背后的知识体系与答题思路,帮助读者从原理层面系统复习,并应对实际开发中的复杂场景。 阅读详情

相关推荐

顺丰科技安卓笔试真题解析:从Handler到内存泄漏的核心考点

在安卓开发中,掌握系统底层机制与性能优化是构建稳定应用的关键。从Java基础如HashMap与GC,到Android核心组件生命周期与启动模式,再到Handler消息机制、ANR与内存泄漏治理,这些技术共同构成了工程师必备的知识体系。理解它们不仅有助于高效开发多任务、多页面应用,更是应对大厂技术笔试与面试的核心能力。顺丰科技2019秋招安卓笔试客观题合集,正是围绕这些高频考点设计,通过典型题目剖析出题逻辑与易错点,帮助开发者查漏补缺,巩固基本功。

weixin_34364071的博客 324

Handler机制

一些基础: handler主要用于在子线程中经行耗时操作避免阻塞UI线程再把消息发送到UI线程再经行处理,handler机制中海包括了Looper,MessageQueue,ThreadLocal等。 Looper: handler一般的写法为: private Handler handler = new Handler(Looper.myLooper()) { @Override public void handleMessage(@NonNull Mes

Z2LYYYY的博客 1016

ArcMap 10.7/10.8启动加载界面后闪退?可能是这个隐藏的Normal.mxt模板文件在搞鬼

本文深入分析了ArcMap 10.7/10.8启动加载界面后闪退的问题,指出Normal.mxt模板文件损坏是常见原因。提供了从定位、删除模板文件到系统级修复的完整解决方案,帮助GIS工程师快速恢复工作流程。

weixin_28523493的博客 348

Handle源码分析

因为只有主线程能修改UI组件,所以主线程又被称作UI线程;但是若只由主线程来修改UI的话,这样会导致新启动的线程无法动态改变UI的属性值或者是进行耗时操作,主线程会被阻塞(ANR异常,系统无法响应输入事件和BroadCast),而子线程又不能修改UI组件,只能在新进程里发出一通消息,这时就需要采用handle的传递机制; Handle的作用有两个:在新启动的线程发送消息(一般采用sendEmpt...

emmmsuperdan的博客 1378

手把手教你用DCA1000EVM解析IWR6843毫米波雷达数据(附MATLAB代码)

本文提供了一份详尽的实战指南,手把手教你使用DCA1000EVM采集并解析TI毫米波雷达IWR6843的原始数据。内容涵盖硬件连接配置、mmWave Studio参数设置、LVDS数据流结构解析,并附有核心MATLAB代码,详细演示了从原始二进制文件到距离-速度谱的信号处理全链路,帮助开发者快速掌握数据解析与处理的关键步骤。

terraform7cloud的博客 241

结构光三维重建2——多频外差解包裹

本文深入解析了结构光三维重建中的多频外差解包裹技术。针对四步相移法产生的相位包裹问题,该方法通过投影多组不同频率的条纹光,利用外差原理逐级解算,最终获得精确、连续的绝对相位值,是实现高精度、稳健三维重建的关键步骤。

weixin_29056101的博客 364

Android Handler消息机制详解(附带源码)

Handler消息机制主要涉及到四个类:Handler、Looper、MessageQueue以及Message。下面将介绍基本概念,并通过源码来深入讲解其原理(源码版本:Android 11.0(R,30))。 1.基本概念: 1.1 Looper循环者 Looper:Looper是安卓消息循环的核心,它主要有以下职责: 负责创建并维护消息队列(MessageQueue mQueue); 关联调用线程(执行Looper.prepare方法的线程); 在关联的线程中启动消息循环(message

z372574152的博客 453

ROS Motion Planning运动规划库安装方法及进阶使用方法详细介绍

​今天偶然发现了一个优质的运动规划库:ai-winter/ros_motion_planning,比较适合从事ROS移动机器人运动规划研究领域的小伙伴学习和使用,相比于莱斯大学Kavraki实验室提供的开源的著名运动规划库OMPL、或着我之前介绍过的zhm-real开源的zhm-real/MotionPlanning和zhm-real/PathPlanning运动规划库,今天介绍的ROS Motion Planning运动规划库与ROS机器人中常用的Navigation导航框架的兼容性更好,库中的运动规划

慕羽★的博客 5588

android中的构造方法,Android 11推荐使用Handler的构造方法

背景Android 11(即API 30:Android R)弃用了Handler默认的无参构造方法 源代码(android.os.Handler)//API 30,Android 11/*** Default constructor associates this handler with the {@link Looper} for the* current thread.** If this...

weixin_39541227的博客 289

使用机器学习算法预测黄金价格

在本文中,我们将使用线性回归、XGBoost和LSTM这三种不同的机器学习算法来预测黄金价格。接下来,我们使用线性回归、XGBoost和LSTM分别建立了模型,并进行了训练和预测。这些机器学习算法可以帮助我们对黄金价格进行预测,但请注意,市场价格受多种因素影响,因此预测结果可能并不完全准确。接下来,我们需要对数据进行一些预处理,以便用于机器学习模型的训练和测试。我们将使用80%的数据作为训练集,20%的数据作为测试集。最后,我们将绘制每个模型的预测结果,并将其与实际价格进行比较,以评估模型的性能。

QromMatlab的博客 1324

YOLOv5算法改进(22)— 更换主干网络MobileNetv3 + 添加CA注意力机制

本节课就让我们结合论文来对YOLOv5进行组合改进(更换主干网络MobileNetv3 + 添加CA注意力机制),小白必学~!🌈

小哥谈 2826

android Handler/Looper 总结

Title Link android中handler用法总结 http://blog.sina.com.cn/s/blog_77c6324101016jp8.html android消息处理机制handler与message http://blog.csdn.net/ahuier/article/details/17012005

一步一步走 1640

PD3.0详解 协议的时序timer和counter计数

前面介绍了关于PD协议的交互,还有协议层数据各个字段的含义,但是一直没有系统的说关于协议的时序,还有部分counter,就是协议允许发送的次数,或者一些其他计数。 大师匈今天说一下关于这方面的东西,这些东西都是非常关键的东西,但是相对来说PD标准内对时序的要求还是比较宽泛,非常容易能够实现这样的要求。 Timer 1、CRCReceiveTimer 0.9~1.1ms 表示每次通信收到goodcrc的时间,必须在这个时间内收到goodcrc, 我们要注意不是在0.9~1.1ms内,而是第三方可以在这个范

大师匈的博客 5019

【Android】Handler 深度解析

Handler机制详解 前言 Handler可以说贯穿了整个Android系统,在Android中扮演着相当重要的角色。我们开发中接触到的四大组件如Activity、Service、BroadcastReceive、ContentProvider,他们的生命周期的管理都是由handler机制进行的,甚至毫不夸张的说,Android几乎所有的操作 ,都与Handler有关。 因此Handler对于Android来说,非常非常重要。所以本篇文章将带大家深入研究Handler的机制。 而我们在开发的过程中,用得比

yang553566463的博客 3289

信捷PLC XD5系列运动控制(10轴)编程应用篇

项目PLC采用XD5-60T10-E,36DI 24DO 晶体管输出,支持10路脉冲输出功能。TMR指令定时器时基可以自己设定,这点比其他品牌PLC方便。ZRN指令我们需要上升沿指令触发。 5、变址寻址 该说不说这个变址寻址是真的强,比西门子指针、三菱的变址寄存器Z 、V都要更加灵活。 7、特殊寄存器:时钟 8、如何建立PLC通讯...............

RXXW_Dor的博客 1万+

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Android组件系列:Handler机制详解

Android Handler机制是每个Android开发者成长道路上一道绕不过去的坎,了解Handler机制对于解决开发中的遇到的卡顿检测、ANR监控,以及了解APP组件是如何运行的等问题有着非常大的帮助市面上已经有许多讲解Handler机制的文章,各种角度的都有,其中不乏有不少深度好文;本文不讲解源码(主要是讲不过其他文章),从Android Handler机制的设计思想开始讲起,由浅入深,带你一步步走进Handler内部的实现原理提到消息队列,自然而然就会想到生产者-消费者模式,在。

1620

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

网易有道安卓二面翻车复盘:无实习非科班如何死磕Handler与Binder源码

在Android开发岗的面试中,Handler消息机制与Binder跨进程通信是绕不开的高频考点。Handler通过Looper死循环与nativePollOnce阻塞-唤醒机制实现线程切换,而Binder借助mmap内存映射完成一次拷贝,从而提升IPC效率。理解这些底层原理,不仅是应对面试连环追问的关键,更是设计健壮缓存、优化应用性能、搭建图片加载库等工程实践的基础。无论是主线程消息调度、进程间通信还是生命周期管理,都离不开对源码级实现逻辑的把握。本文真实复盘一位无实习、非科班的211学生投递网易有道安卓

weixin_33770878的博客 386

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

深度剖析handler消息机制

很多人面试肯定都被问到过,请问Android中的Looper , Handler , Message有什么关系?本篇博客目的首先为大家从源码角度介绍3者关系,然后给出一个容易记忆的结论。 1、 概述 Handler 、 Looper 、Message 这三者都与Android异步消息处理线程相关的概念。那么什么叫异步消息处理线程呢? 异步消息处理线程启动后会进入一个无限的循环体之中,每循

weixin_39779085的博客 246

Android Framework面试核心:Binder与Handler机制深度解析

Binder机制作为Android跨进程通信的核心技术,其线程池管理与内存引用机制直接影响系统稳定性。通过分析Binder线程池的同步阻塞特性与RemoteCallbackList的自动清理机制,可以解决跨进程回调中的内存泄漏问题。Handler消息队列模型则涉及ThreadLocal存储原理,合理使用HandlerThread与LifecycleObserver能有效避免内存泄漏。这些Framework层核心技术在大厂面试中常以实际架构问题形式考察,如设计跨进程通知系统或分析Native内存泄漏。掌握Bi

weixin_30412167的博客 444

Android二面高频考点复盘:从八股到源码深度的进阶指南

在Android开发进阶过程中,技术深度与工程实践能力是衡量开发者水平的关键指标。无论是Handler消息机制、OkHttp源码流程,还是Binder进程通信,都是大厂二面中高频出现的考察点,它们共同指向开发者是否真正理解底层原理,而非仅仅停留在API调用层面。同时,Activity启动模式与任务栈的调度逻辑、TCP三次握手等基础细节,也常被用于检验知识体系的完整性与迁移能力。对于缺乏实习经验的开发者而言,通过深度拆解项目中的技术决策与问题排查过程,同样能有效证明工程实战素养。本文结合网易有道Android

weixin_34087307的博客 426

Android校招笔试高频考点与解题策略:从HashMap到Handler机制深度解析

在Android开发者的技术成长路径中,扎实的Java基础和Android核心机制始终是衡量工程能力的关键标尺。无论是集合框架中的HashMap扩容与红黑树转换,还是并发场景下的synchronized与volatile语义,抑或是支撑UI线程运转的Handler消息循环,这些底层原理不仅决定了App的运行性能与稳定性,更是各大厂校招笔试中反复出现的核心考点。理解这些概念的本质,掌握其设计初衷与极端场景下的行为,能够帮助开发者快速定位内存泄漏、ANR、卡顿等线上问题。从Activity生命周期到进程优先级,

weixin_34037173的博客 372

Android高级面试核心考察维度与技术深度解析

在Android开发领域,技术深度与架构能力是衡量工程师水平的关键指标。从操作系统原理层面,Binder机制作为Android特有的IPC方案,通过一次拷贝和引用计数等设计,在性能与安全性上显著优于传统IPC方式。消息机制中的Handler/Looper体系则利用ThreadLocal实现线程隔离,配合同步屏障等进阶特性支撑复杂场景。这些核心技术不仅影响应用性能指标如启动速度、内存占用,更直接关系到ANR等稳定性问题的排查效率。高级开发者需要掌握从源码层理解系统机制,并能在组件化架构设计、性能优化工具链运用

weixin_34348805的博客 620

京东校招Android主观题全解析:Handler、Binder与性能优化核心考点

在Android技术面试中,考察重点逐渐从API使用转向对底层原理和工程架构的深度理解。Handler消息机制是理解主线程与异步通信的基石,其背后的Looper与MessageQueue设计体现了Android系统的核心调度思想;Binder作为跨进程通信的主力,则展现了系统在性能与安全间的平衡。掌握这些原理不仅有助于回答面试中的追问,更能指导日常开发中的性能优化,例如通过内存泄漏治理和卡顿排查提升应用稳定性。从自定义View的绘制流程到图片加载库的架构设计,再到MVP/MVVM的演进,这些知识点共同构成了

weixin_33894640的博客 348

京东Android真题复盘:从Java基础到Handler机制与AMS

Android开发岗位的笔试与面试,往往从Java基础与系统机制两个层面同时考察候选人的工程功底。在Java集合、并发编程等基础概念之上,理解HashMap的扩容与树化阈值、volatile的内存语义,是写出稳定代码的前提;而Handler的消息循环、Activity启动模式与AMS的进程管理,则决定了能否定位线上复杂问题。随着工程化程度加深,Gradle构建工具链、代码混淆与R8规则、性能优化也成为高频考点。这些技术不仅支撑电商类App的高并发场景与多版本适配,更是校招笔试和社招回炉的关键得分点。本文以京

weixin_34393428的博客 353

分析Android Framework源码--彻底了解Android AudioFocus机制,肯定有你不知道的知识点(基于Android10.0)

一.引言 今天我们来说说Android Audio系统中一套十分重要的机制-AudioFocus机制。AudioFoucs机制的设计主要是为了解决每个音源之间播放冲突的问题。下面呢让我们从源码的角度深度剖析一下AndroidFocus机制。 二.AudioService 在说AudioFocus机制之前有必要先了解一下AudioManager和AudioService这两个类。了解Android服务的朋友都知道,Android自带的系统服分为native服务和Java层服务,Java层服务我们了解最深的应该

braintt的博客 5556

小米2019秋招安卓B卷复盘:核心考点与原理深度解析

Android开发面试中,Activity启动模式、Handler消息机制、自定义View绘制流程始终是高频考点,其背后涉及的组件生命周期、内存优化与UI渲染原理,直接决定了应用的质量与稳定性。理解Handler内存泄漏需要从消息队列引用链与弱引用机制入手,而自定义View的MeasureSpec处理不当则会导致wrap_content失效。与此同时,随着设备形态多样化,多屏适配、安卓Launcher开发等场景成为新的工程挑战,要求开发者具备更全面的知识体系。以小米2019秋招安卓笔试题B卷为线索,系统梳理

weixin_34214500的博客 449
上一篇: Android应用实现开机自启动
下一篇: 鸿蒙应用开发实战(一):应用程序包概述
zdj_develop
博客等级 码龄11年 56粉丝 109原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值