1.public void onClick(View v) {
Thread t = new Thread(){
public void run(){
// Long time comsuming operation
}
};
t.start();
}
public void onClick(View v) {
Thread t = new Thread(){
public void run(){
// Long time consuming operation
_activity.runOnUiThread(new Runnable() {
@Override
public void run() {
_activity.setStatus("Long Operation Completed");
}
});
}
};
t.start();
}
2.
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
@Override
public void run() {
// Long time consuming operation
status.post(new Runnable() {
@Override
public void run() {
status.setText("Long Operstion Completed");
}
});
}
};
t.start();
}
3.
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
@Override
public void run() {
// Long time consuming operation
status.postDelayed(new Runnable() {
@Override
public void run() {
status.setText("Long Operstion Completed");
}
}, 1000);
}
};
t.start();
}
4.
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
// Code to process the response and update UI.
}
};
public void onClick(View v) {
Thread t = new Thread(){
public void run(){
// Long time comsuming operation
Message myMessage=new Message();
Bundle resBundle = new Bundle();
resBundle.putString("status", "SUCCESS");
myMessage.obj=resBundle;
handler.sendMessage(myMessage);
}
};
t.start();
}
5.
public class LongTimeConsumingOperation extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
// perform Long time consuming operation
return null;
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
/* (non-Javadoc)
* @see android.os.AsyncTask#onProgressUpdate(Progress[])
*/
@Override
protected void onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
public void onClick(View v) {
new LongTimeConsumingOperation().execute("");
}
本文介绍了在Android应用中如何正确地从后台线程更新用户界面的方法。包括使用runOnUiThread、View.post、Handler发送消息以及AsyncTask等不同方式来实现长时间运行操作后的UI更新。

被折叠的 条评论
为什么被折叠?



