The difference between android runOnUiThread and handler message

The main difference between the two is that runOnUiThread is locked with the new main thread, that is, other new operations will be suspended when new. So it is recommended to use handler +message to handle new operations!

1. Start runOnUiThread to follow the new main thread


new Thread(){

@Override
public void run() {
while (!interrupted()) {
runOnUiThread(new Runnable() {
public void run() {
try {
int i=0;
sleep(1000);
nowdate.setText("Melody Magic Cloud");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
}
});
}
}

}.start();


2. Use handler to follow the new main thread


final Handler handler=new Handler(Looper.getMainLooper()){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what==1) {
nowdate.setText("Current time: "+msg.obj);
}
}
};
new Thread(){
@Override
public void run() {
while(true){
try {
Thread.sleep(1000);
String time=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new Date());
Message.obtain(handler,1,time).sendToTarget();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace ();
}
}
}
}.start();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325528923&siteId=291194637