在 Android 开发中,我们经常需要了解当前编码的逻辑处于哪个线程,因为我们知道,耗时操作应该放在子线程,而 UI 操作则应该在主线程。

当我们封装一些工具类的时候,为了可复用性,需要对当前的线程进行判断,否则如果操作不当,就会抛出异常。

那么,如何判断当前的线程是主线程还是子线程呢?

借助 Looper 我们可以很方便地知道答案:

public boolean isMainThread() {
    return Looper.getMainLooper() == Looper.myLooper();
}

我们也可以利用 Looper 获取当前的线程:

public boolean isMainThread() {
    return Looper.getMainLooper().getThread() == Thread.currentThread();
}

还可以通过 Looper 获取当前线程的 ID 进行比较:

public boolean isMainThread() {
    return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
}

可以看到,Looper 在这三个方法中都起到重要的作用,这就涉及到 Android 的消息机制,简单来说就是只有主线程中 Android 默认为我们构建了 Looper,而在子线程中并没有,所以主线程和子线程当 Looper 是不会相等的,也就可以很方便地知道当前线程是否在主线程中了。