android 定时器

 

package com.android.timer;


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

import com.android.test.R;

public class TimerActivity extends Activity {
 private  static final String TAG ="TimerActivity" ;
 public TextView mTimeview  = null ;
 public Button mStop = null ;
 public boolean flag = true ;
 public Button mStart = null ;
 public Handler mHandler = new HanderTimer();
 public Thread task = new Thread(new Mythread());
 public int time =60;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
     
  super.onCreate(savedInstanceState);
     setContentView(R.layout.count_timer);
     mTimeview = (TextView)findViewById(R.id.tx1);
     mStop = (Button)findViewById(R.id.stop);
    
     mStop.setOnClickListener(new OnClickListener(
       ) {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    flag = false ;
   }
  });
    
     mStart = (Button)findViewById(R.id.start);
     mStart.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
       flag = true ;
       if(!task.isAlive()){
        task.start();
       }
     
    
    
   }
  });
   
   
 }
 @Override
 protected void onDestroy() {
  
  super.onDestroy();
 }
 
 
 class Mythread implements Runnable{

  @Override
  public void run() {

   try {
    

     while (true) {
      
     if(flag) {
      Thread.sleep(1000);
      time = time - 1;
      mHandler.obtainMessage(0, "" + time).sendToTarget();
     }
       
      
     }


   } catch (InterruptedException e) {

    e.printStackTrace();
   }
  }
  
 }
 class HanderTimer extends Handler{

  @Override
  public void handleMessage(Message msg) {
   Log.d("print", "handle");
   mTimeview.setText(msg.obj.toString());
  }
  
  
 }
}

你可能感兴趣的:(android 定时器)