Android's UI action is not thread-safe, which means that if there are multiple threads concurrently manipulating UI components that can lead to thread-safety issues, Android has a simple rule that allows the UI thread to modify only the UI components in the activity. If other threads are going to modify the UI component, an exception is thrown, and a simple example demonstrates:
Implement the Click button 5 seconds later, adapt the TextView text.
Packagecn.lixyz.handlertest;Importandroid.app.Activity;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.view.View;ImportAndroid.widget.Button;ImportAndroid.widget.TextView; Public classMainactivityextendsActivity {PrivateTextView TextView; Privatebutton button; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); TextView=(TextView) Findviewbyid (R.id.text); Button=(Button) Findviewbyid (R.id.button); Button.setonclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {NewThread () {@Override Public voidrun () {Super. Run (); Try{sleep (5000); Textview.settext ("The text after the change"); } Catch(interruptedexception e) {e.printstacktrace (); }}}.start (); } }); }}
Mainactivity.java
<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"Tools:context=". Mainactivity "> <TextViewAndroid:id= "@+id/text"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center"Android:layout_margintop= "30DP"Android:text= "@string/hello_world"android:textsize= "50DP" /> <ButtonAndroid:id= "@+id/button"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_gravity= "Center"Android:layout_margintop= "30DP"Android:text= "Click I change Text" /></LinearLayout>
Activity_main.xml
If you encode it as above, after 5 seconds of clicking the button, you will be prompted with an error:
and throws an exception:
09-15 03:28:33.964 5854-6002/cn.lixyz.handlertest e/androidruntime:fatal exception:thread-112 5854 only the original thread that created a view hierarchy can touch it views. At Android.view.ViewRootImpl.checkThread (Viewrootimpl.java:6024) at Android.view.ViewRootImpl.requestLayout (Viewrootimpl.java:820) ...
Android Note (29) handler mechanism in Android