How to detect UI thread on Android?

后端 未结 6 694
终归单人心
终归单人心 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-12 19:01

    As of API level 23 the Looper has a nice helper method isCurrentThread. You could get the mainLooper and see if it's the one for the current thread this way:

    Looper.getMainLooper().isCurrentThread()
    

    It's practically the same as:

    Looper.getMainLooper().getThread() == Thread.currentThread()
    

    but it could be a bit more readable and easier to remember.

提交回复
热议问题