-1

I am a newer to android, I read the blog, many people said we can not update the view in other thread, we have to update it in ui thread, what is the reason, why it reports exception when we do it? can anynoe give the reason

Lenoarod
  • 3,441
  • 14
  • 25
kobe23
  • 17
  • 6
  • 1
    You can find the answer here: https://stackoverflow.com/questions/3652560/what-is-the-android-uithread-ui-thread – Yang Liu Nov 27 '19 at 14:01
  • It's quite simple to resolve too, as long as you remember. – Rodrigo Arias Roberts Nov 27 '19 at 14:21
  • @YangLiu, I want to know why the view has to update views in the UI thread. not about concept. – Lenoarod Nov 27 '19 at 14:21
  • 1
    Based the concept, we can tell that the UI thread is designed and dedicated for code related to application components including views. It's more like a choice. In terms of why this choice is made, there could be some discussion. – Yang Liu Nov 27 '19 at 14:36

1 Answers1

1

in the last weeks, I read the source code about how to add the view to the window.

when we call setContentView set view, it actually calls the window.setContentView and in the end, ActivityThread.handleResumeActivity will call the activity onResume method, the view shows. we look at handleResumeActivity method. it will call activity makeVisible method.

...
if (r.activity.mVisibleFromClient) {
                r.activity.makeVisible();
            }
...
// the makeVieible will call wm.addView method
void makeVisible() {
        if (!mWindowAdded) {
            ViewManager wm = getWindowManager();
            wm.addView(mDecor, getWindow().getAttributes());
            mWindowAdded = true;
        }
        mDecor.setVisibility(View.VISIBLE);
    }
// this metod in the last called WindowGolbal.addView;then in the inner method;
// it will call ViewRootImpl.setView, in this method, it calls requestLayout
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
...
// Schedule the first layout -before- adding to the window
                // manager, to make sure we do the relayout before receiving
                // any other events from the system.
                requestLayout();
}

@Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }
void checkThread() {
        if (mThread != Thread.currentThread()) {
            throw new CalledFromWrongThreadException(
                    "Only the original thread that created a view hierarchy can touch its views.");
        }
    }

so we find here it reminds us we can not update the view. the system does that make the UI show smooth and updates view simple. if many threads can update it. it is a bad thing. because It has to handle the concurrency problem

Lenoarod
  • 3,441
  • 14
  • 25