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