Android判断当前是否在主线程

Android开发中, 有时需要判断当前线程到底是主线程, 还是子线程, 例如: 我们在自定义View时, 想要让View重绘, 需要先判断当前线程到底是不是主线程, 然后根据判断结果来决定到底是调用 invalidate() 还是 postInvalidate() 方法. 如果当前是主线程, 就调用 invalidate() 方法; 而如果当前是子线程, 就调用 postInvalidate() 方法, 注意: 子线程中不能调用 invalidate() 方法, 否则就会报异常, 提示我们不能在子线程中更新UI。

那么, 我们如何判断当前线程到底是主线程, 还是子线程呢? 答案是: 可以借助于 Looper. 代码如下:

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

或者

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

或者

public boolean isMainThread() {
    return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
}
原文地址:https://www.cnblogs.com/genggeng/p/7524948.html