Handler主线程子线程之间的互相通信
Handler主线程子线程之间的互相通信
1 package com.wyl.dansnote; 2 3 4 import android.app.Activity; 5 import android.os.Bundle; 6 import android.os.Handler; 7 import android.os.Looper; 8 import android.os.Message; 9 import android.view.View; 10 import android.view.View.OnClickListener; 11 import android.widget.Button; 12 import android.widget.Toast; 13 14 public class SecActivity extends Activity implements OnClickListener{ 15 Button btn_main_to_work; 16 Button btn_work_to_main; 17 Handler handler; 18 Handler handler_main_to_work; 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.sec_main); 23 initViews(); 24 initMainHandler();//子线程向主线程发送消息 25 new MainToWorkThread().start();//主线程向子线程发送消息 26 initClicks(); 27 } 28 29 30 private void initMainHandler() { 31 handler = new MainHandler(); 32 } 33 class MainHandler extends Handler{ 34 @Override 35 public void handleMessage(Message msg) { 36 String msg_rtn = (String)msg.obj; 37 // System.out.print("MainHandler.handleMessage():"+msg_rtn+",当前线程:"+Thread.currentThread().getName()); 38 Toast.makeText(SecActivity.this, "MainHandler.handleMessage():"+msg_rtn+",当前线程:"+Thread.currentThread().getName(), 100).show(); 39 } 40 } 41 //子线程向主线程发送消息 42 class WorktoMainThread extends Thread{ 43 @Override 44 public void run() { 45 Message msg = handler.obtainMessage(); 46 msg.obj = "我是模拟的网络数据"; 47 handler.sendMessage(msg); 48 System.out.println("开始发送网络数据:"); 49 //暂时还不清楚为什么这个线程里使用Toast的时候一定要加上Looper.prepare(),否则就报错 50 // Looper.prepare(); 51 // Toast.makeText(SecActivity.this, Thread.currentThread().getName()+"开始发送网络数据:", 100).show(); 52 } 53 } 54 55 class MainToWorkThread extends Thread{ 56 @Override 57 public void run() { 58 Looper.prepare(); 59 handler_main_to_work = new Handler(){ 60 @Override 61 public void handleMessage(Message msg) { 62 String msg_get = (String)msg.obj; 63 // handler_main_to_work.sendMessage(msg); 64 Toast.makeText(SecActivity.this, Thread.currentThread().getName()+",MaintoWorkHandler.handleMessage()开始接收消息:"+msg_get, 100).show(); 65 } 66 }; 67 Message msg = handler_main_to_work.obtainMessage(); 68 String msg_get = (String) msg.obj; 69 System.out.println("MainToWorkThread获取到的消息:"+msg_get); 70 Looper.loop(); 71 } 72 } 73 74 private void initClicks() { 75 btn_main_to_work.setOnClickListener(this); 76 btn_work_to_main.setOnClickListener(this); 77 } 78 79 private void initViews() { 80 btn_main_to_work = (Button) findViewById(R.id.id_btn_w_to_main); 81 btn_work_to_main = (Button) findViewById(R.id.id_btn_main_to_w); 82 } 83 84 @Override 85 public void onClick(View v) { 86 switch (v.getId()) { 87 case R.id.id_btn_w_to_main: 88 new WorktoMainThread().start(); 89 break; 90 case R.id.id_btn_main_to_w: 91 Message msg = handler_main_to_work.obtainMessage(); 92 msg.obj = "我是点击的时候发送给子线程的消息"; 93 handler_main_to_work.sendMessage(msg); 94 break; 95 default: 96 break; 97 } 98 } 99 }