方法一:View.post(Runnable action)
public void onClick( View v ) {
new Thread( new Runnable() {
public void run() {
// 耗时操作
doLongOperation();
myText.post(new Runnable() {
myText.setText( 来自网络的信息);
});
}
}).start();
}
方法二:Activity.runOnUiThread(Runnable action)
与view.post()方法类似
public void onClick( View v ) {
new Thread(new Runnable() {
public void run() {
// 耗时操作
doLongOperation();
Activity.runOnUiThread(new Runnable() {
myText.setText( 来自网络的信息);
});
}
}).start();
}
方法三:Handler
子线程调用Handler的sendMessage(Message message)方法发送消息
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 更新界面
myText.setText(接收到的Message);
}
};
public class MyThread extends Thread {
public void run() {
// 耗时操作
doLongOperation();
Message msg = new Message();
mHandler.sendMessage(msg);
}
}
方法四:AsyncTask
// UI线程中执行
new DownloadImageTask().execute("");
private class LoadTask extends AsyncTask {
protected String doInBackground(String... url) {
return loadDataFormNetwork( url[0] );//后台耗时操作
}
protected void onPostExecute(String result) {
myText.setText( result ); //得到来自网络的信息刷新页面
}
}