Android线程间通信的Message机制
2010-06-01 15:44:00 来源:WEB开发网Looper myLooper, mainLooper;
myLooper = Looper.myLooper();
mainLooper = Looper.getMainLooper(); //这是一个static函数
String obj;
if(myLooper == null){
mNoLooperThreadHandler = new EventHandler(mainLooper);
obj = "NoLooperThread has no looper and handleMessage function executed in main thread!";
}
else {
mNoLooperThreadHandler = new EventHandler(myLooper);
obj = "This is from NoLooperThread self and handleMessage function executed in NoLooperThread!";
}
mNoLooperThreadHandler.removeMessages(0);
if(false == postRunnable){
//send message to main thread
Message m = mNoLooperThreadHandler.obtainMessage(2, 1, 1, obj);
mNoLooperThreadHandler.sendMessage(m);
Log.e(sTag, "NoLooperThread id:" + this.getId());
}else{
//下面new出来的实现了Runnable接口的对象中run函数是在Main Thread中执行,不是在NoLooperThread中执行
//注意Runnable是一个接口,它里面的run函数被执行时不会再新建一个线程
//您可以在run上加断点然后在eclipse调试中看它在哪个线程中执行
mNoLooperThreadHandler.post(new Runnable(){
@Override
public void run() {
tv.setText("update UI through handler post runnalbe mechanism!");
noLooerThread.stop();
}
});
}
}
}
//OwnLooperThread has his own message queue by execute Looper.prepare();
class OwnLooperThread extends Thread{
private EventHandler mOwnLooperThreadHandler;
public void run() {
Looper.prepare();
Looper myLooper, mainLooper;
myLooper = Looper.myLooper();
mainLooper = Looper.getMainLooper(); //这是一个static函数
String obj;
if(myLooper == null){
mOwnLooperThreadHandler = new EventHandler(mainLooper);
更多精彩
赞助商链接