public class MainActivity extends ActionBarActivity {
Timer m_timer = null;
TimerTask m_task = null;
Handler handler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startButton = (Button)findViewById(R.id.start_timer);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startTimer();
}
});
Button stopButton = (Button)findViewById(R.id.finish_timer);
stopButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stopTimer();
}
});
}
private void startTimer(){
if (null == m_timer){
m_timer = new Timer();
}
if (null == handler){
handler = new Handler(){
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:{
// to do something
timerWorking();
}
break;
default:
break;
}
super.handleMessage(msg);
}
};
}
if (null == m_task){
m_task = new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
}
if (m_timer != null && m_task != null){
m_timer.schedule(m_task, 0, 1000);//1秒执行一次
}
}
private void timerWorking(){
Log.d("TimerTest","Timer is working");
}
private void stopTimer(){
if (null != m_timer){
m_timer.cancel();
m_timer = null;
}
if (null != m_task){
m_task.cancel();
m_task = null;
}
if (null != handler){
handler = null;
}
Log.d("TimerTest","Timer is stopped");
}
}
设置了两个按钮 一个是开始timer 一个是结束timer xml在下
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:text="开启Timer"
android:id="@+id/start_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:text="结束Timer"
android:id="@+id/finish_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>