Android进阶宝典 -- 解读Handler机制核心源码,让ANR无处可藏

lxf2023-12-21 01:30:02

其实,写这篇文章的初衷还是上一篇关于ANR问题分析的时候,想到其实ANR核心本质就是让UI线程(主线程)等了太久,导致系统判定在主线程做了耗时操作导致ANR。当我们执行任何一个任务的时候,在Framework底层是通过消息机制来维护任务的分发,从下面这个日志可以看到,

"main" prio=5 tid=1 Blocked
  | group="main" sCount=1 dsCount=0 flags=1 obj=0x7583df30 self=0xe36f4000
  | sysTid=6084 nice=-10 cgrp=default sched=0/0 handle=0xe83b5494
  | state=S schedstat=( 4210489664 1169737873 12952 ) utm=123 stm=298 core=2 HZ=100
  | stack=0xff753000-0xff755000 stackSize=8MB
  | held mutexes=
  at com.lay.datastore.DataStoreActivity.onCreate$lambda-1(DataStoreActivity.kt:29)
  - waiting to lock <0x0493299a> (a java.lang.Object) held by thread 15
  at com.lay.datastore.DataStoreActivity.$r8$lambda$IFZrCDzOUja7d5eTPj5Nq-CEC-8(DataStoreActivity.kt:-1)
  at com.lay.datastore.DataStoreActivity$$ExternalSyntheticLambda0.onClick(D8$$SyntheticClass:-1)
  at android.view.View.performClick(View.java:6597)
  at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1219)
  at android.view.View.performClickInternal(View.java:6574)
  at android.view.View.access$3100(View.java:778)
  at android.view.View$PerformClick.run(View.java:25885)
  at android.os.Handler.handleCallback(Handler.java:873)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:193)
  at android.app.ActivityThread.main(ActivityThread.java:6669)

每个任务执行,都是通过Handler来分发消息,一旦任务阻塞无法执行下去,那么就会导致main thread被挂起,就是Blocked状态,所以掌握Handler的事件分发机制,对于我们分析ANR日志会有很大的帮助。

1 Handler的事件分发机制

我们知道,UI的刷新必须要在主线程,而对于耗时操作,例如网络请求,往往都是发生在子线程,所以对于数据的刷新必须要涉及到线程切换,像Rxjava、EventBus、协程,都具备线程的上下文切换的能力,其实归结到底层都是Handler。

1.1 sendMessage方法分析

我们在使用Handler的时候,通常都是创建一个Handler对象,在handleMessage中接收其他线程发送来的消息。

class HandlerActivity : AppCompatActivity() {

    private val handler by lazy {
        Handler(Looper.getMainLooper()) { message ->

            when (message.what) {
                1 -> {

                }
            }
            return@Handler true
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_handler)

        Thread {
            handler.sendEmptyMessage(1)
        }.start()
    }
}

那么在子线程中,发送消息的方式都是sendxxx方法,看下图:

Android进阶宝典 -- 解读Handler机制核心源码,让ANR无处可藏

如此多的send方法,我们肯定都熟悉他们的用法,通过源码我们可以看到,每个方法最终都调用了sendMessageAtTime方法。

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

在这个方法中,首先拿到了一个MessageQueue对象,这个是一个消息队列,具体数据结构稍后分析,然后调用了enqueueMessage方法。

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

enqueueMessage从字面意思上,就是将消息入列,即将消息插入消息队列;首先会给Message对象添加一个target属性,这个需要注意一下,因为我们可能会创建多个Handler,那么这个target属性就标记了消息最终交给哪个Handler处理,这里就有可能发生内存泄漏。

最后调用了MessageQueue的enqueueMessage方法;

boolean enqueueMessage(Message msg, long when) {
    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 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;
}

我们看到这里是一个同步方法,因为存在多个线程的消息入队,所以这里是线程安全的;在enqueueMessage方法中传入了一个when参数,这个参数的作用就是消息在入队的时候,会根据执行时间的先后进行排队,根据时间先后依次执行,这样子线程的消息发送就完成了。

总结一下:子线程调用send方法时,其实就是将数据封装为Message结构体,往消息队列中插入这条message消息就完成任务了,剩下的就交给子线程来处理。

1.2 Android系统心跳机制

当子线程将消息入队之后,主线程怎么去取的呢?当app启动之后,系统会通过zygote进程fork出一个app进程,剩下的启动任务就交给ActivityThread来完成,通过反射调用了ActivityThread的main方法。

public static void main(String[] args) {

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

在main方法中,其实就是创建了Looper对象,调用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.");
    }
    if (me.mInLoop) {
        Slog.w(TAG, "Loop again would have the queued messages be executed"
                + " before this one completed.");
    }

    me.mInLoop = true;

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

    me.mSlowDeliveryDetected = false;

    for (;;) {
        if (!loopOnce(me, ident, thresholdOverride)) {
            return;
        }
    }
}

这里开启的死循环,可以理解为Android系统的一个心跳机制,通过死循环不断地取出消息处理消息,保证我们这个进程是活着的。当然回到文章开头说的,当处理消息发生阻塞性问题时,就会导致ANR。

private static boolean loopOnce(final Looper me,
        final long ident, final int thresholdOverride) {
    Message msg = me.mQueue.next(); // might block
    if (msg == null) {
        // No message indicates that the message queue is quitting.
        return false;
    }

    // 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);
    }
    // ......
    
    try {
        msg.target.dispatchMessage(msg);
        if (observer != null) {
            observer.messageDispatched(token, msg);
        }
        dispatchEnd = needEndTime ? SystemClock.uptimeMillis() : 0;
    } catch (Exception exception) {
        if (observer != null) {
            observer.dispatchingThrewException(token, msg, exception);
        }
        throw exception;
    } finally {
        ThreadLocalWorkSource.restore(origWorkSource);
        if (traceTag != 0) {
            Trace.traceEnd(traceTag);
        }
    }
    // .. 

    return true;
}

我们可以看到,在死循环中,会重复调用loopOnce方法,在这个方法中,会从MessageQueue中不断取出Message,在子线程消息入队的时候,设置了target属性,我们看到最终其实在消息处理的时候,就是调用了Handler的dispatchMessage方法。

1.3 dispatchMessage方法分析

我们简单看下dispatchMessage的代码,很简单,大致分为3种类型。

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

1.3.1 如果Message的callback对象不为空;

什么情况下,会对Message的callback参数赋值?我们看下handleCallback的源码,最终执行了callback的run方法,其实就是执行了Runnable的run方法。

private static void handleCallback(Message message) {
    message.callback.run();
}

我们看下Handler的post方法,在这个方法中其实就是传入了一个Runnable对象,


public final boolean post(@NonNull Runnable r) {
   return  sendMessageDelayed(getPostMessage(r), 0);
}

然后getPostMessage方法中,也是创建了一个Message对象,并将Runnable对象作为callback参数赋值。

private static Message getPostMessage(Runnable r) {
    Message m = Message.obtain();
    m.callback = r;
    return m;
}

也就是说,当子线程调用post方法的时候,就会走到这部分逻辑中,通过这种方式可以实现线程的切换。

1.3.2 如果mCallback不为空;

从Handler的构造函数中中,发现可以传入一个Callback对象,

public Handler(@NonNull Looper looper, @Nullable Callback callback, boolean async) {
    mLooper = looper;
    mQueue = looper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}
public interface Callback {
    /**
     * @param msg A {@link android.os.Message Message} object
     * @return True if no further handling is desired
     */
    boolean handleMessage(@NonNull Message msg);
}

Callback是一个接口,内部方法为handleMessage,也就是说如果在Handler中传入了Callback对象,那么就会使用Callback的handleMessage进行消息处理;如果没有传入Callback,那么就直接调用handleMessage,类似于文章开头那种使用方式,当然大部分场景下,我们都会这样使用。

所以通过子线程消息发送,主线程处理消息,我们大概就能明白Handler跨线程的本质,两者之间就是通过MessageQueue作为纽带来关联起来的,类似于一个传送带,而MessageQueue是什么时候创建的呢?

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

在创建Looper的时候就已经创建了,既然是在主线程创建,那么MessageQueue就是在主线程,子线程就可以往这个队列中插入Message,主线程调用MessageQueue的next方法去获取自然也是在主线程了。

2 Handler处理多线程并发问题

前面,我们提到的都是常规用法,在主线程中创建Handler,在主线程中进行消息的处理,主要用于子线程发送数据,主线程更新UI,那么我们只能在主线程创建Handler吗?如果在子线程中创建Handler,需要做什么处理?

2.1 子线程创建Handler

像下面这样,我们能直接在子线程中创建Handler对象吗?

Thread {
    val handler = Handler{
        
        return@Handler true
    }
}.start()

我们看下Handler的构造函数源码,在判断逻辑处,

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();
    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的时候,是从sThreadLocal对象中取,它其实是一个与线程相关的Map集合,在调用get方法的时候,会以当前线程为key,获取对应的Looper对象。

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

像主线程中的Looper对象,其实就是在ActivityThread中创建并加入到主线程中的ThreadLocal中,其实就是调用了下面的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对象,对应一个MessageQueue,所以如果在子线程中想要创建Handler对象,就必须要调用prepare方法。

ok,那么我们可以这样使用,就先调用一下Looper的prepare方法不就行了吗?

Thread {
    Looper.prepare()
    val handler = Handler{
        return@Handler true
    }
    Looper.loop()
}.start()

这样写法正确吗?是不对的!我们是在匿名内部类中调用了prepare方法,但是线程对象是无法获取到的,就无法在ThreadLocal中存储对应的Looper对象。

所以这个时候,就需要自行创建一个Thread子类,

class MyHandlerThread : Thread() {

    private var mLooper: Looper? = null

    override fun run() {
        super.run()
        Looper.prepare()
        mLooper = Looper.myLooper()
        Looper.loop()
    }

    fun getLooper(): Looper? {
        return mLooper
    }
}

这样当MyHandlerThread运行之后,子线程的Looper也就顺利创建了。

val handlerThread = MyHandlerThread()
handlerThread.start()
//第三行
val handler = Handler(handlerThread.getLooper()!!){

    return@Handler true
}

因为这部分都是在主线程中创建的,但是Looper的创建以及存储都是在线程中进行,那么第三行代码执行时,如何保证getLooper时拿到了已经创建的Looper,这就涉及到了线程同步的问题。

加延迟?太low了。

class MyHandlerThread : Thread() {

    private var mLooper: Looper? = null
    private var lock = java.lang.Object()

    override fun run() {
        super.run()
        Looper.prepare()
        synchronized(lock){
            Log.e("TAG","开始创建Looper----")
            mLooper = Looper.myLooper()
            //创建完成
            Log.e("TAG","创建Looper完成,唤醒----")
            lock.notifyAll()
        }
        Looper.loop()
    }

    fun getLooper(): Looper? {
        synchronized(lock){
            while (mLooper == null){
                Log.e("TAG","获取Looper失败,mLooper == null 等待----")
                lock.wait()
            }
        }
        Log.e("TAG","获取Looper成功")
        return mLooper
    }
}

处理线程的并发问题,自然要想到锁机制,其实这里我们只需要在获取和创建的时候加锁,当在获取Looper对象的时候,就会判断Looper是否创建成功,如果没有就调用wait释放锁,等待创建成功之后,就返回。

2023-04-22 14:00:04.244 10067-10067/com.lay.layzproject E/TAG: 获取Looper失败,mLooper == null 等待----
2023-04-22 14:00:04.247 10067-10124/com.lay.layzproject E/TAG: 开始创建Looper----
2023-04-22 14:00:04.250 10067-10124/com.lay.layzproject E/TAG: 创建Looper完成,唤醒----
2023-04-22 14:00:04.253 10067-10067/com.lay.layzproject E/TAG: 获取Looper成功

这才是子线程创建Handler的正确姿势,当然系统也帮我们提供了对应的HandlerThread类,不需要我们自己去自定义。

2.2 消息队列中无消息时,主线程和子线程如何优雅处理

我们先看子线程,因为我们Looper是在子线程中创建的,所以MessageQueue也是在子线程处理消息,

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

            // 核心代码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;
    }
}

当从MessageQueue中取出消息时,会调用next方法,如果消息队列中为空,那么会调用nativePollOnce方法,此时线程就处于Block的状态,此时退出页面时,线程不会被回收会导致内存泄漏。

所以,想要解决这个问题,就需要在页面退出之后,调用Looper的quitSafely方法,

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

其实最终是调用了MessageQueue的quit方法,在这个方法中,会把mQuitting = true,并调用了nativeWake方法,其实跟nativePollOnce是相对应的;

在nativePollOnce处于block时,调用nativeWake会唤醒,并继续往下执行,执行到核心代码1时,因为mQuitting = true,所以直接return,并调用dispose。

在loopOnce方法中,如果调用next方法拿到了msg为空,直接return退出for循环,那么此时线程也就执行结束了,最终被回收掉。

主线程可以这么处理吗?显然不行!如果主线程都被退出了,那么整个app将无法运行,所以在quit方法中,

Main thread not allowed to quit

第一行代码就在判断,如果是主线程就不能退出。

2.3 Handler如何保证多线程安全

因为我们在创建Handler之后,在通过Handler发送消息的时候,可能会在不同的线程,那么Handler是如何保证线程安全的呢?

其实我们前面提到过,假设是在主线程创建Handler,那么Looper就是在ActivityThread的main函数中创建的,此时在sThreadLocal中,维护的就是<main,mainLooper>这样的映射关系,也就是说一个线程只能有一个looper对象,如果连续创建就会报错,可以看下Looper的prepare源码。

因为MessageQueue也是在Looper的构造方法中创建,也就是说 线程 - Looper - MessageQueue 是意义对应的关系,不会存在多个,所以核心就在于消息的入队;通过enqueueMessage方法,我们发现在入队的时候,其实是加锁的,拿到的是MessageQueue的对象锁,因为MessageQueue只有一个,所有的线程都会竞争这把锁,所以都是互斥的。

即便是创建多个Handler,也是同理。

3 Handler与ANR的恩怨情仇

3.1 Handler的消息阻塞机制

当主线程阻塞超过5s之后,就会触发ANR;前面我们知道,在Looper开启死循环取消息的时候,如果消息队列中没有消息的时候,就可能会被block,调用了nativePollOnce,那么为什么没有阻塞主线程呢?

其实我们应该把这分为两件事来看,looper.loop是用来处理消息,当没有消息的时候,主线程就休息了,不需要干任何事;像input事件,其实就是一个Message,当它加入到消息队列的时候,会调用nativeWake唤醒主线程,主线程来处理这个消息,只有处理这个消息超时,才会发生ANR,而不是死循环会导致ANR。

3.2 ANR日志中看Handler消息机制

"main" prio=5 tid=1 Native
  | group="main" sCount=1 dsCount=0 flags=1 obj=0x7185b6a8 self=0xb400007375b4bbe0
  | sysTid=3433 nice=0 cgrp=default sched=0/0 handle=0x749c9844f8
  | state=S schedstat=( 800801640 66783841 881 ) utm=60 stm=19 core=0 HZ=100
  | stack=0x7fc20cb000-0x7fc20cd000 stackSize=8192KB
  | held mutexes=
  native: #00 pc 000000000009ca68  /apex/com.android.runtime/lib64/bionic/libc.so (__epoll_pwait+8)
  native: #01 pc 0000000000019d88  /system/lib64/libutils.so (android::Looper::pollInner(int)+184)
  native: #02 pc 0000000000019c68  /system/lib64/libutils.so (android::Looper::pollOnce(int, int*, int*, void**)+112)
  native: #03 pc 0000000000112194  /system/lib64/libandroid_runtime.so (android::android_os_MessageQueue_nativePollOnce(_JNIEnv*, _jobject*, long, int)+44)
  at android.os.MessageQueue.nativePollOnce(Native method)
  at android.os.MessageQueue.next(MessageQueue.java:335)
  at android.os.Looper.loop(Looper.java:183)
  at android.app.ActivityThread.main(ActivityThread.java:7723)
  at java.lang.reflect.Method.invoke(Native method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:997)

在我们分析ANR日志时,经常会看到这样表现,结合上面我们对于Handler的了解,这个时候其实就是没有消息了,我们看已经调用了nativePollOnce方法,此时主线程就休眠了,等待下一个消息到来。

"main" prio=5 tid=1 Blocked
  | group="main" sCount=1 dsCount=0 flags=1 obj=0x7185b6a8 self=0xb400007375b4bbe0
  | sysTid=3906 nice=-10 cgrp=default sched=0/0 handle=0x749c9844f8
  | state=S schedstat=( 2591708189 61276010 2414 ) utm=220 stm=38 core=5 HZ=100
  | stack=0x7fc20cb000-0x7fc20cd000 stackSize=8192KB
  | held mutexes=
  // ...... 
  - waiting to lock <0x0167ghe6d> (a java.lang.Object) held by thread 5
  // ...... 方法调用,保密
  at android.os.Handler.handleCallback(Handler.java:938)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:223)
  at android.app.ActivityThread.main(ActivityThread.java:7723)
  at java.lang.reflect.Method.invoke(Native method)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:612)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:997)

在这段日志中,我们看到主线程已经是出问题了,处于Blocked的状态,那么在Handler调用dispatchMessage方法的时候,是调用了handleCallback,说明此时是调用了post方法,在post方法中,主线程一直想要获取其他线程持有的一把锁,导致了超时产生了ANR。

从日志看,就能知道,其实ANR跟Looper.loop完全就是两回事。

其实Handler作为面试中的高频问点,对于其中的原理我们需要掌握,尤其是多线程并发的原理,可能是很多伙伴们忽视的重点。

最近刚开通了微信公众号,各位伙伴可以搜索【layz4android】,或者扫码关注,每周不定时更新,也有惊喜红包