先把效果贴出来,我点击第一个button让主线程开始发送消息,点击第二个button时将handler移除,我没实现,想实现的可以自己去操作!!
private Button button1;
private Button button2;
/**
* 主线程的handler
*/
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
//随便发送一个空的消息,延迟3秒发送
Message message = new Message();
System.out.println("Main Thread");
threadHandler.sendMessageDelayed(message, 3000);
};
};
/**
* 子线程的hanlder
*/
private Handler threadHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.threadtomain_act);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
//使用HandlerThread
HandlerThread thread = new HandlerThread("Thread Handler");
thread.start();
//创建一个新的handler,用于子线程中,给子线程创建一个looper对象
threadHandler = new Handler(thread.getLooper()) {
public void handleMessage(android.os.Message msg) {
//随便发送一个空的消息,延迟3秒发送
Message message = new Message();
System.out.println("Thread");
handler.sendMessageDelayed(message, 3000);
};
};
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1://向子线程发送消息
handler.sendEmptyMessage(1);
break;
case R.id.button2://移除当前消息
handler.removeMessages(1);
break;
}
}