android使用handler ui线程和子线程通讯更新ui示例
package com.act262.sockettx;
import android.app.activity;
import android.os.bundle;
import android.os.handler;
import android.os.message;
import android.view.view;
import android.view.view.onclicklistener;
import android.widget.button;
import android.widget.edittext;
import android.widget.textview;
/**
* 可以在其他线程中获取view类的数据,但是不能修改或者设置view类的数据
*
*/
public class main extends activity {
textview result = null;
edittext get = null;
button update = null;
handler handler;
public void oncreate(bundle bundle) {
super.oncreate(bundle);
setcontentview(r.layout.main);
result = (textview) findviewbyid(r.id.result);
update = (button) findviewbyid(r.id.update);
get = (edittext) findviewbyid(r.id.get);
handler = new handler() {
public void handlemessage(message msg) {
if (msg.what == 1) {
result.settext("after update ui "
+ msg.getdata().getstring("data")
+ " \nman thread : "
+ thread.currentthread().getname());
}
}
};
result.settext("before update ui main thread : "
+ thread.currentthread().tostring());
update.setonclicklistener(new onclicklistener() {
@override
public void onclick(view v) {
// todo auto-generated method stub
new mythread("my thread").start();
}
});
}
class mythread extends thread {
public mythread(string name) {
super(name);
}
@override
public void run() {
// 发送不带数据的消息
// handler.sendemptymessage(1);
// 发送附带数据的消息
message msg = new message();
bundle data = new bundle();
data.putstring("data", get.gettext().tostring() + " my thread: "
+ thread.currentthread().getname());
msg.setdata(data);
msg.what = 1;
handler.sendmessage(msg);
}
}
}