测试Timer

测试Android中Timer使用MainActivity,以下只是一个简简单单的测试工程,关于Timer的详细讲解在这里
package com.einverne.testtimer;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

 private static String TAG = "EV_DEBUG";
 private Timer timer;
 Integer integer;

 private TextView tv;
 private Button button_start;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  tv = (TextView) findViewById(R.id.textView_time);
  button_start = (Button) findViewById(R.id.button_start);

  integer = new Integer(0);
  new TimeThread().start();

  findViewById(R.id.button_start).setOnClickListener(
    new OnClickListener() {

     @Override
     public void onClick(View v) {
      // TODO Auto-generated method stub
      timer = new Timer();
      integer = 0;
      timer.schedule(new timerTask(), 0, 1000);
      button_start.setEnabled(false);
     }
    });

  findViewById(R.id.button_end).setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    timer.cancel();
    button_start.setEnabled(true);
   }
  });
  
  

 }

 public class timerTask extends TimerTask {

  @Override
  public void run() {
   // TODO Auto-generated method stub
   integer++;
   String time = integer.toString();
   Log.d(TAG, time);
  }
 }

 public class TimeThread extends Thread {
  Handler handler = new Handler() {
   @Override
   public void handleMessage(Message msg) {
    super.handleMessage(msg);
    switch (msg.what) {
    case 1:
     tv.setText(integer.toString());
     break;

    default:
     break;
    }
   }
  };
  @Override
  public void run() {
   do {
    try {
     Thread.sleep(1000);
     Message msg = new Message();
     msg.what = 1;
     handler.sendMessage(msg);

    } catch (InterruptedException e) {
     e.printStackTrace();
    }

   } while (true);
  }
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }

}

Related Articles

Quote Of The Day