How to detect UI thread on Android?

后端 未结 6 689
终归单人心
终归单人心 2020-12-12 18:38

Is there a robust way to detect if Thread.currentThread() is the Android system UI thread in an application?
I would like to put some asserts in my model co

6条回答
  •  天命终不由人
    2020-12-12 19:13

    Besides checking looper, if you ever tried to logout thread id in onCreate(), you could find the UI thread(main thread) id always equals to 1. Therefore

    if (Thread.currentThread().getId() == 1) {
        // UI thread
    }
    else {
        // other thread
    }
    

提交回复
热议问题