The UI cannot be operated in the AndroidStudio sub-thread

  Opened a sub-thread in the main thread today, the following code

 public class MainActivity extends AppCompatActivity {
  Thread thread;
  boolean threadExit = false;

  public TextView tv1;
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv1 = (TextView)this.findViewById(R.id.textView2);
    thread = new Thread() {
       @Override
       public void run() {
         super.run();
         while (!threadExit) {
         tv1.setText("test");
         try {
             Thread.sleep(3000);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
      }
    }
   };
  }
}

However, the following problems occurred when running, the UI cannot be operated in the sub-thread

 

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
        at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7313)
        at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1161)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.view.View.requestLayout(View.java:21995)
        at android.support.constraint.ConstraintLayout.requestLayout(ConstraintLayout.java:3172)
        at android.view.View.requestLayout(View.java:21995)
        at android.widget.TextView.checkForRelayout(TextView.java:8531)
        at android.widget.TextView.setText(TextView.java:5394)
        at android.widget.TextView.setText(TextView.java:5250)
        at android.widget.TextView.setText(TextView.java:5207)
        at com.indemind.indeminddesktopapp.MainActivity$1.outputState(MainActivity.java:154)
        at com.indemind.indeminddesktopapp.MainActivity$1.run(MainActivity.java:76)

After checking the relevant information, I found that the message can be sent in the run () method, and sent using the handler. First, create an internal class


 class  MyHandle extends Handler
 {
   @Override
   public void handleMessage(Message msg)
   {
     super.handleMessage(msg);
     String str = (String)msg.obj;
     tv1.setText(str);

   }
 }

Then, in the child thread

thread = new Thread() {
  @Override
  public void run() {
    super.run();
    while (!threadExit) {
     // tv1.setText("test");
     Message msg = Message.obtain();
     msg.obj ="TestSucceed"
     handle.sendMessage(msg);
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
};

In this way, UI setText(str) can be performed in the child thread

Guess you like

Origin blog.csdn.net/zjw1349547081/article/details/85265515