How to know if this thread is a UI Thread

前端 未结 4 961
走了就别回头了
走了就别回头了 2021-02-05 06:28

Is there any way on Android to know, if the thread running my code, is the UI Thread or not ? In swing there was SwingUtilities.isEventDispatchThread() to tell me

4条回答
  •  遥遥无期
    2021-02-05 06:58

    1. Answer borrowed from here: How to check if current thread is not main thread

      Looper.myLooper() == Looper.getMainLooper()

    2. Any Android app has only one UI thread, so you could somewhere in the Activity callback like onCreate() check and store its ID and later just compare that thread's ID to the stored one.

      mMainThreadId = Thread.currentThread().getId();

    3. Anyway, you can omit checking if you want to do something on the UI thread and have any reference to Activity by using

      mActivity.runOnUiThread( new Runnable() {
          @Override 
          public void run() {
          ...
          }
      });
      

    which is guaranteed to run on current thread, if it's UI, or queued in UI thread.

提交回复
热议问题