Android线程间通信的Message机制
2010-06-01 15:44:00 来源:WEB开发网ownLooperThread = new OwnLooperThread();
ownLooperThread.start();
break;
case 104:
//other thread通过Post Runnable方式发送消息给主线程
postRunnable = true;
noLooerThread = new NoLooperThread();
noLooerThread.start();
break;
case 105:
//主线程发送消息给other thread
if(null!=mOtherThreadHandler){
tv.setText("please look at the error level log for other thread received message from main thread");
String msgObj = "message from mainThread";
Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);
mOtherThreadHandler.sendMessage(mainThreadMsg);
}
break;
case 106:
finish();
break;
}
}
class EventHandler extends Handler
{
public EventHandler(Looper looper) {
super(looper);
}
public EventHandler() {
super();
}
public void handleMessage(Message msg) {
//可以根据msg.what执行不同的处理,这里没有这么做
switch(msg.what){
case 1:
tv.setText((String)msg.obj);
break;
case 2:
tv.setText((String)msg.obj);
noLooerThread.stop();
break;
case 3:
//不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息
Log.e(sTag, (String)msg.obj);
ownLooperThread.stop();
break;
default:
//不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息
Log.e(sTag, (String)msg.obj);
break;
}
}
}
//NoLooperThread
class NoLooperThread extends Thread{
private EventHandler mNoLooperThreadHandler;
public void run() {
更多精彩
赞助商链接