Android 三种实现定时器详解及实现方法

  package com.xunfang.handerDemo;

  import android.app.Activity;

  import android.os.Bundle;

  import android.os.Handler;

  import android.os.Message;

  import android.widget.TextView;

  /**

  * handler定时器

  *

  * @author Smalt

  *

  */

  public class HanderDemoActivity extends Activity {

  TextView tvShow;

  private int i = 0;

  @Override

  public void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.main);

  tvShow = (TextView) findViewById(R.id.tv_show);

  new Thread(new ThreadShow()).start();

  }

  // handler类接收数据

  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() {

  // TODO Auto-generated method stub

  while (true) {

  try {

  Thread.sleep(1000);

  Message msg = new Message();

  msg.what = 1;

  handler.sendMessage(msg);

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

  } catch (Exception e) {

  // TODO Auto-generated catch block

  e.printStackTrace();

  System.out.println("thread error...");

  }

  }

  }

  }

  }