1. First we use an example case to elicit an exception:
(1) Layout file activity_main.xml:
1 <Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"2 Xmlns:tools= "Http://schemas.android.com/tools"3 Android:layout_width= "Match_parent"4 Android:layout_height= "Match_parent"5 Tools:context=". Mainactivity " >6 7 <TextView8 Android:id= "@+id/tv"9 Android:layout_width= "Wrap_content"Ten Android:layout_height= "Wrap_content" One Android:layout_centerhorizontal= "true" A android:layout_centervertical= "true" - Android:text= "@string/hello_world" /> - the </Relativelayout>
(2)Mainactivity.java:
PackageCom.itheima.testthread;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.os.Message;ImportAndroid.widget.EditText;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); System.out.println (Thread.CurrentThread (). GetName ()); FinalTextView TV =(TextView) Findviewbyid (r.id.tv); NewThread () { Public voidrun () { for(inti = 0; I < 100; i++) {Tv.settext ("Hahaha" +i); Try{Thread.Sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); } } }; }.start (); }}
(3) The deployment procedure to the simulator, the following effect, the program directly stop; and report the exception error directly:
Error:
android.view.viewrootimpl$calledfromwrongthreadexception: Only the original thread, that created a view Hierarchy can touch its views.
Meaning: The exception that is called from the wrong thread. Who created the view, who can modify the edit view, only the main thread can modify the view (all view is created by the main thread).
Summary: This calledfromwrongthreadexception error is reported because only the main thread can modify the view update UI, but here we create a new thread for ourselves () where the contents of run () involve updating the UI, This is not allowed, and all this error warning will occur.
But often when we write programs to design multiple threads need to control the UI display, but we have said that UI updates can only be handed to the main thread, in order to resolve this contradiction, the liberation of programmers,Google developed a message mechanism for the child thread and the main thread communication, To update the UI, the child thread sends the message data to the main thread so that the main thread updates the corresponding UI interface to resolve the contradiction .
Android (Java) Learning Note 202: The principle and implementation of message mechanism