使用Handler消息傳遞機(jī)制脖律;
使用AsyncTask異步任務(wù)仓技;
使用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();
總結(jié):
1医舆、其實(shí)上面的四種方式都可歸結(jié)于一種方式:handler 用于Android線(xiàn)程之間的通信。
2象缀、為什么android要求只能在UI線(xiàn)程進(jìn)行UI操作蔬将? 主要還是為了避免多線(xiàn)程造成的并發(fā)的問(wèn)題。在單線(xiàn)程操作UI是安全的央星。