How to know if this thread is a UI Thread

前端 未结 4 960
走了就别回头了
走了就别回头了 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:49

    Yes, there is a way. Check the current thread object against main lopper's thread object. Main looper is always in the UI thread.

    boolean isOnUiThread = Thread.currentThread() == Looper.getMainLooper().getThread();
    
    0 讨论(0)
  • 2021-02-05 06:50

    Put a breakpoint where you want to check and, when it gets hit, check if you can interact with your UI (ie, if the UI is not frozen). If you can't interact with the UI then you are in the UI Thread, otherwise you are in a background thread.

    0 讨论(0)
  • 2021-02-05 06:51

    Hum actually due to Android architecture, all Activities run in the main thread, ie the UI thread. So when you are coding an activity, everything that is in your Activity is in the UI thread.
    That is why in Honeycomb an error have been added when you are making network calls in the main thread : it totally blocks the UI.

    So by default you are in fact always working in the UI thread. Another thing : unless you explicitely ask it to be in another thread, a Service will operate on the same thread as the activities of its application.

    So, what to do ?

    • When you have to do heavy calculation in your activity; one solution is to use an AsyncTask (a class designed to allow you to easily use another thread). The code in onExecute() is run in another thread (but be cautious postExecute runs in your main thread). Another one is to manually start a new thread when AsyncTask is not really adapted.
    • If you create a service that does costly background tasks, make it run in another thread with the android:process=":my_process" attribute of the manifest. You will need to create an AIDL to communicate with this separated service, but it is not a complicated task.
    • Many objects, like for example the MediaPlayer, have Async variations of their methods. Try to to always use them.
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题