子线程向另外一个子线程使用handler发送消息
Thread nThread = new Thread() {
@Override
public void run() {
Looper.prepare(); //获取当前线程的Looper,并prepare();
mhandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.arg1 == 1) {
Log.v("mthread", "click" + Thread.currentThread().getName());
Toast.makeText(HandleThreadActivity.this, "handler msg", Toast.LENGTH_SHORT).show();
}
}
};
Looper.loop(); //looper开始处理消息。
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handle_thread);
btn = (Button) findViewById(R.id.btn);
nThread.start();
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.v("mthread", "MainThread" + Thread.currentThread().getName());
myThread = new MyThread();
myThread.start();
}
}
);
}
private class MyThread extends Thread {
@Override
public void run() {
Log.v("mthread", "start" + Thread.currentThread().getName());
try {
Thread.sleep(1000);
Message msg = new Message();
msg.arg1 = 1;
mhandler.sendMessage(msg);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}