Why does my child thread update the UI without an error? Take this to correct a knowledge misunderstanding of some Android programmers

Source: Internet
Author: User

Straight:

The misconception is that a child thread cannot update the UI, and it should be categorized, rather than absolute.

Half an hour ago, in my Xrecyclerview group, a group of friends privately chat me, the question is:

Why does my child thread update the UI without an error?

I asked him to send out the code I see, like next, very simple code.
@Overrideprotected void onCreate(Bundle savedinstancestate) {Super.onCreate(savedinstancestate);Setcontentview(R.Layout.Activity_main); title = (TextView)Findviewbyid(R.ID.title_tips);Doget("Http;//www.baidu.com",NewCallback () {@Override         Public void onfailure(Request request, IOException e) {                    }@Override         Public void Onresponse(Response Response)throwsIOException {title.SetText(Response.Body().string());//Here The text is updated in the child thread}    });}Private void Doget(String url,callback Callback) {Okhttpclient client =New okhttpclient(); Request.BuilderBuilder =NewRequest.Builder(); Request Request = Builder.URL(URL).Get().Build(); Client.Newcall(Request).Enqueue(callback);}

Simple parsing. He used the OkHttp asynchronous Enqueue request and updated the text of TextView after success.

Be clear:
    • Okhttp synchronous asynchronous callbacks are all within a child thread.

So, according to what we've been taught to do: a sub-thread can't refresh the UI, and the code above is properly blown up and wrong.

And what I'm going to say is:

The above code is not necessarily a bad error, it will be stable and smooth execution.

You really doubt it?

You can try it next. Too troublesome, you can run 通透 a sub-thread under this section to update the UI code

 Public classTestactivityextendsActivity {PrivateTextView title;@Override    protected void onCreate(Bundle savedinstancestate) {Super.onCreate(savedinstancestate);Setcontentview(R.Layout.Activity_main); title = (TextView)Findviewbyid(R.ID.title_tips);NewThread (NewRunnable () {@Override                     Public void Run() {//Sub-thread update UITitle.SetText("I'm done with the TM."); }                }        ).Start(); }}

Tried to know that the real TM executed the error.

Is it upside down? Reason

In seeing the code that he sent me, the onCreate parts inside, everything was clear, and this was the pit of the people I had been interviewing for years of experience. Below I directly tell the reason, source analysis those you go to see it, 你应该去看 .

    • The restriction that a child thread cannot update the UI is Viewrootimpl.java internal limit

      voidcheckThread() {// 该方法是 viewRootImpl.java 内部代码if (mThread != Thread.currentThread()) {    thrownewCalledFromWrongThreadException(            "Only the original thread that created a view hierarchy can touch its views.");}}
    • For component Activity, the initialization of Viewrootimpl after OnCreate, after Onresume.
    • If your child thread update code meets the following conditions, it will run smoothly:
      • Modify the application layer's Viewrootimpl.java source code, remove the restrictions
      • Write your update code before onresume, such as onCreate, and update it before Viewrootimpl initialization.
Modify Validation---Throw an error
@Overrideprotected void onCreate(Bundle savedinstancestate) {Super.onCreate(savedinstancestate);Setcontentview(R.Layout.Activity_main); title = (TextView)Findviewbyid(R.ID.title_tips);NewThread (NewRunnable () {@Override                 Public void Run() {Try{//wait for Onresume to finish, let Viewrootimpl initialization completeThread.Sleep( the);//----------here, look here.}Catch(Interruptedexception e) {e.Printstacktrace(); } title.SetText("I can't do it."); }            }    ).Start();}
Finish

Why does my child thread update the UI without an error? Take this to correct a knowledge misunderstanding of some Android programmers

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.