其实,写这篇文章的初衷还是上一篇关于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】,或者扫码关注,每周不守时更新,也有惊喜红包哦,也能够后台留言感兴趣的专题,给各位同伴们产出文章。