read");
btn4.setOnClickListener(this);
layout.addView(btn4, params);
btn5 = new Button(this);
btn5.setId(105);
btn5.setText("main thread's message to other thread");
btn5.setOnClickListener(this);
layout.addView(btn5, params);
btn6 = new Button(this);
btn6.setId(106);
btn6.setText("exit");
btn6.setOnClickListener(this);
layout.addView(btn6, params);
tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setText("");
params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
params.topMargin=10;
layout.addView(tv, params);
setContentView(layout);
receiveMessageThread = new ReceiveMessageThread();
receiveMessageThread.start();
}
class EventHandler extends Handler{
public EventHandler(Looper looper){
super(looper);
}
public EventHandler(){
super();
}
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Log.e(TAG, "CurrentThread id:----------+>" + Thread.currentThread().getId());
switch(msg.what){
case 1:
tv.setText((String)msg.obj);
break;
case 2:
tv.setText((String)msg.obj);
noLooperThread.stop();
break;
case 3:
//不能在非主线程的线程里面更新UI,所以这里通过log打印信息
Log.e(TAG,(String)msg.obj);
ownLooperThread.stop();
break;
default:
Log.e(TAG,(String)msg.obj);
break;
}
}
}
//ReceiveMessageThread has his own message queue by execute Looper.prepare();
class ReceiveMessageThread extends Thread {
@Override
public void run(){
Looper.prepare();
mOtherThreadHandler= new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
Log.e(TAG,"-------+>"+(String)msg.obj);
Log.e(TAG, "CurrentThread id:----------+>" + Thread.currentThread().getId());
}
};
Log.e(TAG, "ReceiveMessageThread id:--------+>" + this.getId());
Looper.loop();
}
}
class NoLooperThread extends Thread {
private EventHandler mNoLooperThreadHandler;
@Override
public void run() {
Looper myLooper = Looper.myLooper();
Looper mainLooper= Looper.getMainLooper();
String msgobj;
if(null == myLooper){
//这里获得的是主线程的Looper,由于NoLooperThread没有自己的looper所以这里肯定会被执行
| 评论 |
|
|