How to know if this thread is a UI Thread

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

提交回复
热议问题