private Thread1 mThread1 ;
private Thread2 mThread2 ;
//先进行子线程之间的通信测试
public class Thread1 extends Thread{
private Handler handler1;
public Handler getHandler(){//注意哦,在run执行之前,返回的是null
return handler1;
}
@Override
public void run() {
Looper.prepare();
handler1 = new Handler(){
public void handleMessage(android.os.Message msg) {
//这里处理消息
Log.i("MThread1", "收到消息了:"+Thread.currentThread().getName()+"----"+msg.obj);
};
};
Looper.loop();
}
}
public class Thread2 extends Thread{
@Override
public void run() {
for(int i=0; i<10; i++){
Message msg = Message.obtain();
msg.what = 1;
msg.obj = System.currentTimeMillis()+"";
mThread1.handler1.sendMessage(msg);
Log.i("MThread2", Thread.currentThread().getName()+"----发送了消息!"+msg.obj);
sendMessage(2, "可以考虑双发送数据??") ; //这个是发送给主线程的消息
SystemClock.sleep(1000);
}
}
}
public static void sendMessage(int what, Object obj) {
if (mHandler != null)
mHandler.obtainMessage(what, obj).sendToTarget();
}
private static Handler mHandler= new Handler(){
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case HANDLER_MSG_TOAST:
case 2:
Message msg2 = Message.obtain();
msg2.what = 2;
msg2.obj = "主线程发送来的消息";
mThread1.handler1.sendMessage(msg2);
// showToast("接收到数据了");
Log.i("mainHander", "接收到数据"+msg.obj);
break;
}
}
};
上面的测试基本实现了,在主线程和子线程之间实现消息互发处理任务。