Android定时器实现的几种方式整理及removeCallbacks失效问题解决

  package com.example.demoactivity;

  import android.app.Activity;

  import android.os.Bundle;

  import android.os.Handler;

  import android.view.View;

  import android.view.View.OnClickListener;

  import android.widget.Button;

  public class TimerActivity extends Activity{

  Handler handler = new Handler();

  Runnable runnable = new Runnable() {

  @Override

  public void run() {

  System.out.println("update...");

  handler.postDelayed(runnable, 1000);

  }

  };

  @Override

  protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.timer);

  Button mButtonStart = (Button) findViewById(R.id.button1);

  Button mButtonStop = (Button) findViewById(R.id.button2);

  mButtonStart.setOnClickListener(new OnClickListener() {

  @Override

  public void onClick(View v) {

  handler.post(runnable);

  }

  });

  mButtonStop.setOnClickListener(new OnClickListener() {

  @Override

  public void onClick(View v) {

  handler.removeCallbacks(runnable);

  }

  });

  }

  }