SoFunction
Updated on 2025-03-11

A summary of how to update UI on Android

1. Activity's runOnUiThread

textView = (TextView) findViewById(  );
new Thread(new Runnable() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
( "Updated UI");
}
});
}
}).start();

Android Activity runOnUiThread() method is used

2、Handler sendEmptyMessage()

package ;
import ;
import ;
import .;
import ;
import ;
public class MainActivity extends AppCompatActivity {
private TextView textView ;
Handler handler = new Handler( ) {
@Override
public void handleMessage(Message msg) {
(msg);
( "Ui updated");
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_main);
textView = (TextView) findViewById(  );
new Thread(new Runnable() {
@Override
public void run() {
try {
( 2000 );
} catch (InterruptedException e) {
();
}
( 2 ) ;
}
}).start();
}
}

3、Handler post()

package ;
import ;
import ;
import .;
import ;
public class MainActivity extends AppCompatActivity {
private TextView textView ;
Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
(savedInstanceState);
setContentView(.activity_main);
textView = (TextView) findViewById(  );
new Thread(new Runnable() {
@Override
public void run() {
try {
( 2000 );
} catch (InterruptedException e) {
();
}
(new Runnable() {
@Override
public void run() {
( "Ui updated");
}
}) ;
}
}).start();
}
}

4、view Post() 

textView = (TextView) findViewById(  );
new Thread(new Runnable() {
@Override
public void run() {
try {
( 2000 );
} catch (InterruptedException e) {
();
}
(new Runnable() {
@Override
public void run() {
( "Ui updated");
}
}) ;
}
}).start();

Summarize:

1. In fact, the above four methods can be attributed to one method: handler is used for communication between Android threads.

2. Why does Android require that UI operations can only be performed on UI threads? The main purpose is to avoid the concurrency problem caused by multithreading. Operating the UI in a single thread is safe.

The above is the summary of the Android update UI methods introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message. The editor will reply to you in time!