1. What is a UI thread? Is the UI thread equal to the main thread?
1.1 Activity# runOnUiThread
If the current application component is an Activity, we often do this when we refresh the UI in the child thread
public final void runOnUiThread(Runnable action) {
if(Thread.currentThread() ! = mUiThread) { mHandler.post(action); }else{ action.run(); Final void attach(Context Context){mUiThread = thread.currentThread (); }Copy the code
==mUiThread == == == == == == == == == == == == == == == == == == == == == =
1.2 the post
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if(attachInfo ! = null) {return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on whichThread it needs to run. // Assume that the runnable will be successfully placed after attach. // It is possible that viewrotimpl has not been created getRunQueue().post(action);return true;
}
/**
* A Handler supplied by a view's {@link android.view.ViewRootImpl}. This * handler can be used to pump events in the UI events queue. */ final Handler mHandler;Copy the code
Here AttachInfo was created when the ViewRootImpl was created, so it’s in the main thread, and mHandler is the Handler that was created in the main thread, so refreshing the UI is also switched to the main thread. == For a View, its UI thread is the same thread as the ViewRootImpl thread ==, and if it does not refresh the UI in this thread it will throw an exception
1.3 How is the UI thread started
This is the start of main() for ActivityThread, which involves the message loop.
-
What is a UI thread?
-
How is the UI message loop created?
Can you briefly say how the application process is startedCopy the code
-
The relationship between UI threads and UI architecture
Talk about ViewRootImplCopy the code
Keep in mind that this does not mean that you cannot refresh the UI in child threads, as shown in the following example:
new Thread(){
public void run(){
Looper.prepare();
getWindowManager.addView(view, params);
Looper.loop();
}
}.start()
Copy the code
In this example, we are adding a View to a DecorView in a child thread, and refreshing the UI should be in the child thread. Refreshing the UI in the main thread instead throws an exception.
void checkThread() {
if(mThread ! = Thread.currentThread()) { throw new CalledFromWrongThreadException("Only the original thread that created a view hierarchy can touch its views."); }}Copy the code
We must remember the nature of this anomaly. Essentially, the thread that refreshes the current UI must be the same as the thread that added the current UI. That is, if your UI is added in the main thread (such as the UI in a regular Activity), you refresh it in the main thread, whereas if your UI is added in a child thread (such as the example above), Then you need to refresh in the child thread. == series of threads