android USES multithreading to update the ui sample share

  • 2020-05-19 05:54:56
  • OfStack

The technologies involved in the Android thread are: Handler; Message; MessageQueue; Looper; HandlerThread.

Here's a snippet of code that updates UI in a thread:


public class MainActivity extends Activity {
private TextView timeLable;
private Button stopBtn;
private Thread mThread;
private boolean isRunning = true;
private int timeCount = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timeLable = (TextView) findViewById(R.id.timelable);
    stopBtn = (Button) findViewById(R.id.stop);
    stopBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {               
            isRunning = false;
        }
    });
    mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (isRunning) {
                try {
                    Thread.sleep(1000);
                    timeCount++;
                    timeLable.setText("timeCount=" + timeCount + "  seconds ");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mThread.start();        
}
}

This code only updates the display of TextView in the thread, but after execution, there is no effect and an error is reported: android.view.ViewRootImpl $CalledFromWrongThreadException: Only the original thread created a hierarchy can touch its its views.
Update UI processing in Android must be updated by the thread that created it and cannot be updated in other threads. That's why it's wrong.

Since timeLable is an UI control, it is created in the main thread, but it is updated in the child thread, and the update is implemented in the run() method of the mThread thread. This processing violates the Android multithreaded programming rules and the system throws an exception.

To solve this problem, define the responsibilities of the main thread and the child threads. The main thread is responsible for creating, displaying, and updating UI controls, handling UI events, starting child threads, stopping child threads, and so on. The responsibility of the child thread is to calculate the time and issue an update UI message to the main thread, rather than directly updating UI. Child threads sending messages to the main thread can be implemented using Handler. The code is as follows:


public class MainActivity extends Activity {
private TextView timeLable;
private Button stopBtn;
private Thread mThread;
private boolean isRunning = true;
private int timeCount = 0;
final private Handler mHandler = new Handler(){
    public void handleMessage(Message msg) {
        switch (msg.what) {
        case 0 :
            timeLable.setText("timeCount=" + timeCount + "  seconds ");
            break;
        default :
            break;
        }
    }
};
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    timeLable = (TextView) findViewById(R.id.timelable);
    stopBtn = (Button) findViewById(R.id.stop);
    stopBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            isRunning = false;
        }
    });
    mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            while (isRunning) {
                try {
                    Thread.sleep(1000);
                    timeCount++;
                    mHandler.sendEmptyMessage(0);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    });
    mThread.start();
}
}

After running, the previous error will not be reported, and TextView can update the content normally.


Related articles: