使用Handler消息传递机制;
使用AsyncTask异步任务;
使用runOnUiThread(action)方法;
使用Handler的post(Runnabel r)方法;
1、Activity的 runOnUiThread
textView = (TextView) findViewById( R.id.tv );
newThread(newRunnable() {
@Override
publicvoidrun() {
runOnUiThread(newRunnable() {
@Override
publicvoidrun() {
textView.setText("更新UI了");
}
});
}
}).start();
android Activity runOnUiThread() 方法使用
2、Handler sendEmptyMessage()
packagelib.com.myapplication;
importandroid.os.Handler;
importandroid.os.Message;
importandroid.support.v7.app.AppCompatActivity;
importandroid.os.Bundle;
importandroid.widget.TextView;
publicclassMainActivityextendsAppCompatActivity {
privateTextView textView ;
Handler handler =newHandler( ) {
@Override
publicvoidhandleMessage(Message msg) {
super.handleMessage(msg);
textView.setText("Ui更新了");
}
};
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById( R.id.tv );
newThread(newRunnable() {
@Override
publicvoidrun() {
try{
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
handler.sendEmptyMessage(2) ;
}
}).start();
}
}
3、Handler post()
packagelib.com.myapplication;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.support.v7.app.AppCompatActivity;
importandroid.widget.TextView;
publicclassMainActivityextendsAppCompatActivity {
privateTextView textView ;
Handler handler =newHandler();
@Override
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById( R.id.tv );
newThread(newRunnable() {
@Override
publicvoidrun() {
try{
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
handler.post(newRunnable() {
@Override
publicvoidrun() {
textView.setText("Ui更新了");
}
}) ;
}
}).start();
}
}
4、view Post()
textView = (TextView) findViewById( R.id.tv );
newThread(newRunnable() {
@Override
publicvoidrun() {
try{
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
textView.post(newRunnable() {
@Override
publicvoidrun() {
textView.setText("Ui更新了");
}
}) ;
}
}).start();
总结:
1、其实上面的四种方式都可归结于一种方式:handler 用于Android线程之间的通信。
2、为什么android要求只能在UI线程进行UI操作? 主要还是为了避免多线程造成的并发的问题。在单线程操作UI是安全的。
网友评论