Android消息机制
2010-09-10 00:43:00 来源:WEB开发网(2)当然需要一个Looper对象,来管理该MessageQueue。
(3)我们可以构造Handler对象来push新消息到Message Queue里;或者接收Looper(从Message Queue取出)所送来的消息。
(4)线程A的Handler对象可以传递给别的线程,让别的线程B或C等能送讯息来给线程A(存于A的Message Queue里)。
(5)线程A的Message Queue里的消息,只有线程A所属的对象可以处理。
子线程传递消息给主线程
public class Activity2 extends Activity implements OnClickListener{
Button button = null;
TextView text = null;
MyHandler mHandler = null;
Thread thread ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
button = (Button)findViewById(R.id.btn);
button.setOnClickListener(this);
text = (TextView)findViewById(R.id.content);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn:
thread = new MyThread();
thread.start();
break;
}
}
private class MyHandler extends Handler{
public MyHandler(Looper looper){
super(looper);
}
@Override
public void handleMessage(Message msg) {//处理消息
text.setText(msg.obj.toString());
}
}
private class MyThread extends Thread{
@Override
public void run() {
Looper curLooper = Looper.myLooper();
Looper mainLooper = Looper.getMainLooper();
String msg ;
if(curLooper==null){
mHandler = new MyHandler(mainLooper);
msg = "curLooper is null";
}else{
mHandler = new MyHandler(curLooper);
msg = "This is curLooper";
}
mHandler.removeMessages(0);
更多精彩
赞助商链接