package com.example.handler01;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class FourActivity extends Activity implements OnClickListener{
//创建主线程的handler
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
Message message = new Message();
System.out.println("main Handler");
//向子线程发送消息
threadHandler.sendMessageDelayed(message, 1000);
};
};
private Handler threadHandler;
private Button button1;
private Button button2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.four);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(this);
button2.setOnClickListener(this);
HandlerThread thread = new HandlerThread("handlerThread");
thread.start();
//创建子线程的handler
threadHandler = new Handler(thread.getLooper()) {
@Override
public void handleMessage(Message msg) {
Message message = new Message();
System.out.println("Thread Handler");
//向主线程发送消息
handler.sendMessageDelayed(message, 1000);
}
};
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
handler.sendEmptyMessage(1);
break;
case R.id.button2:
handler.removeMessages(1);
default:
break;
}
}
}