1. Use the Handler mechanism.
private void one() { handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what){ case 123: tv.setText(""+msg.obj); break; }}}; new Thread(){ @Override public void run() { super.run(); for (int i=0; i<3; i++){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } Message message=new Message(); message.what=123; Message. obj=" via Handler mechanism "; handler.sendMessage(message); } }.run(); }Copy the code
The main thread defines the Handler, and the child thread sends a message telling the Handler to complete the UI update. The Handler object must be defined in the main thread, which is not very convenient if multiple classes call each other directly, so you need to pass the Content object or call it through the interface. In addition, it is not recommended to use the Handler mechanism because it is inconsistent with the Activity life cycle, which may lead to memory leakage.
2. RunOnUiThread method
private void two(){ new Thread(){ @Override public void run() { super.run(); for (int i=0; i<3; i++){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }} runOnUiThread(new Runnable() {@override public void run() {tv.settext (" runOnUiThread "); }}); } }.run(); }Copy the code
Updating with the Activity object’s runOnUiThread method and updating the UI in child threads with the runOnUiThread() method is highly recommended.
3, view. post(Runnable r),
private void three(){ new Thread(){ @Override public void run() { super.run(); for (int i=0; i<3; i++){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }} tv.post(new Runnable() {@override public void run() {tv.settext (" view.post (Runnable r) "); }}); } }.run(); }Copy the code
This method is simpler, but requires passing the View to be updated. 4 AsyncTask is recommended
Private void four(){new MyAsyncTask().execute(" AsyncTask method "); } private class MyAsyncTask extends AsyncTask{ @Override protected Object doInBackground(Object[] objects) { for (int i=0; i<3; i++){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return objects[0].toString(); } @Override protected void onPostExecute(Object o) { super.onPostExecute(o); tv.setText(o.toString()); }}Copy the code