package com.example.handler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
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 msg1 = new Message();
// 向子线程发送消息
handler.sendMessageDelayed(msg1, 1000);
System.out.println("main handler");
Log.d("111", "main handler");
};
};
//子线程的handler
private Handler threadhandler;
private Button bt1;
private Button bt2;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO 自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.four);
bt1 = (Button) findViewById(R.id.button1);
bt2 = (Button) findViewById(R.id.button2);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
HandlerThread thread = new HandlerThread("handler thread");
thread.start();
//创建子线程的handler
threadhandler = new Handler(thread.getLooper()){
@Override
public void handleMessage(Message msg) {
Message msg1 = new Message();
// 向主线程发送消息
handler.sendMessageDelayed(msg1, 1000);
System.out.println("thread handler");
Log.d("222", "thread handler");
}
};
}
@Override
public void onClick(View v) {
// TODO 自动生成的方法存根
switch (v.getId()) {
case R.id.button1:
handler.sendEmptyMessage(1);
break;
case R.id.button2:
handler.removeMessages(1);
break;
default:
break;
}
}
}