android 线程间的通信
2010-08-23 01:12:00 来源:WEB开发网028 // 接收子线程的消息
029 info.setText((String) msg.obj);
030 }
031
032 };
033
034 new ChildThread().start();
035
036
037 msgBtn.setOnClickListener(new OnClickListener() {
038
039 @Override
040 public void onClick(View v) {
041
042 if (mChildHandler != null) {
043
044 //发送消息给子线程
045 Message childMsg = mChildHandler.obtainMessage();
046 childMsg.obj = mMainHandler.getLooper().getThread().getName() + " says Hello";
047 mChildHandler.sendMessage(childMsg);
048
049 Log.i(TAG, "Send a message to the child thread - " + (String)childMsg.obj);
050
051
052 }
053 }
054 });
055
056 }
057
058 public void onDestroy() {
059 super.onDestroy();
060 Log.i(TAG, "Stop looping the child thread's message queue");
061
062 mChildHandler.getLooper().quit();
063 }
064
065 class ChildThread extends Thread {
066
067 private static final String CHILD_TAG = "ChildThread";
068
069 public void run() {
070 this.setName("ChildThread");
071
072 //初始化消息循环队列,需要在Handler创建之前
073 Looper.prepare();
074
075 mChildHandler = new Handler() {
076 @Override
077 public void handleMessage(Message msg) {
078 Log.i(CHILD_TAG, "Got an incoming message from the main thread - " + (String)msg.obj);
079
080
081 try {
082
083 //在子线程中可以做一些耗时的工作
084 sleep(100);
085
086 Message toMain = mMainHandler.obtainMessage();
更多精彩
赞助商链接