回答:
UIスレッドのIDを決定する一般的な方法は、Looper#getMainLooperを使用することです。
if (Looper.getMainLooper().getThread() == Thread.currentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
APIレベル23 以降では、メインルーパーで新しいヘルパーメソッドisCurrentThreadを使用して、もう少し読みやすい方法があります。
if (Looper.getMainLooper().isCurrentThread()) {
// On UI thread.
} else {
// Not on UI thread.
}
APIレベル23以降、Looperこれには素晴らしいヘルパーメソッドがありisCurrentThreadます。あなたはこれを取得してmainLooper、それが現在のスレッドのものかどうかを次のように確認できます:
Looper.getMainLooper().isCurrentThread()
それは実質的に同じです:
Looper.getMainLooper().getThread() == Thread.currentThread()
しかし、少し読みやすく覚えやすいかもしれません。
public boolean onUIThread() {
return Looper.getMainLooper().isCurrentThread();
}
ただし、APIレベル23が必要です
ルーパーをチェックする以外に、スレッドID をログアウトしようとした場合onCreate()、UIスレッド(メインスレッド) IDが常に1に等しいことがわかります。したがって、
if (Thread.currentThread().getId() == 1) {
// UI thread
}
else {
// other thread
}
クラスでrunOnUiThreadメソッドを使用できませんでしたActivityか?