Android 实现定时器的三种方法

    1. Handler+Thread
    1. Handler 自带的 postDelyed 方法
    1. Handler + Timer + TimerTask

1. Handler+Thread

public class HanderDemoActivity extends Activity {

  TextView tvShow;
  private int i = 0;
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvShow = (TextView) findViewById(R.id.tv_show);
    new Thread(new ThreadShow()).start();
  }
   
  // handler类接收数据更新UI
  Handler handler = new Handler() {
    public void handleMessage(Message msg) {
      if (msg.what == 1) {
        tvShow.setText(Integer.toString(i++));
        System.out.println("receive....");
      }
    };
  };
   
  // 线程类发送消息给主线程
  class ThreadShow implements Runnable {
    @Override
    public void run() {
      while (true) {
        try {
          Thread.sleep(1000);
          Message msg = new Message();
          msg.what = 1;
          handler.sendMessage(msg);
          System.out.println("send...");
        } catch (Exception e) { 
            e.printStackTrace();
            System.out.println("thread error...");
        }
      }
    }
  }
}

2. Handler 自带的 postDelyed 方法

public class HanderDemoActivity extends Activity {
  TextView tvShow;
  private int i = 0;
  private int TIME = 1000; // 每隔1s执行
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvShow = (TextView) findViewById(R.id.tv_show);
    handler.postDelayed(runnable, TIME); // 开启定时器更新UI
  }

  Handler handler = new Handler();
  Runnable runnable = new Runnable() {
    @Override
    public void run() {
      // handler自带方法实现定时器
      try {
        handler.postDelayed(this, TIME);
        tvShow.setText(Integer.toString(i++));
        System.out.println("do...");
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println("exception...");
      }
    }
  };
}

3. Handler + Timer + TimerTask

public class HanderDemoActivity extends Activity {

  TextView tvShow;
  private int i = 0;
  private int TIME = 1000;
   
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tvShow = (TextView) findViewById(R.id.tv_show);
    timer.schedule(task, 1000, 1000); // 1s后执行task,经过1s再次执行
  }

  Handler handler = new Handler() {
    public void handleMessage(Message msg) {
      if (msg.what == 1) {
        tvShow.setText(Integer.toString(i++));
      }
      super.handleMessage(msg);
    };
  };

  Timer timer = new Timer();
  TimerTask task = new TimerTask() {
    @Override
    public void run() {
      // 定时任务发送消息
      Message message = new Message();
      message.what = 1;
      handler.sendMessage(message);
    }
  };
}

你可能感兴趣的:(Android 实现定时器的三种方法)