设为首页 加入收藏

TOP

Android Handler Message多线程实例(二)
2014-11-24 11:27:58 来源: 作者: 【 】 浏览:4
Tags:Android Handler Message 线程 实例
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所以这里肯定会被执行
首页 上一页 1 2 3 4 下一页 尾页 2/4/4
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Java创建线程的三种方式 下一篇如何使用Java synchronized进行线..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Python 数据分析与可 (2025-12-26 21:51:20)
·从零开始学Python之 (2025-12-26 21:51:17)
·超长干货:Python实 (2025-12-26 21:51:14)
·为什么 Java 社区至 (2025-12-26 21:19:10)
·Java多线程阻塞队列 (2025-12-26 21:19:07)