时间计时器

package com.example.demo1;

import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.app.Activity;
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 implements OnClickListener {

	private TextView timeTV;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		timeTV = (TextView) findViewById(R.id.tv);
		b = (Button) findViewById(R.id.bt);
		b.setOnClickListener(this);

	}

	@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;
	}

	public String showTimeCount(long time) {
		if (time >= 360000000) {
			return "00:00:00";
		}
		String timeCount = "";
		long hourc = time / 3600000;
		String hour = "0" + hourc;
		hour = hour.substring(hour.length() - 2, hour.length());

		long minuec = (time - hourc * 3600000) / (60000);
		String minue = "0" + minuec;
		minue = minue.substring(minue.length() - 2, minue.length());

		long secc = (time - hourc * 3600000 - minuec * 60000) / 1000;
		String sec = "0" + secc;
		sec = sec.substring(sec.length() - 2, sec.length());
		timeCount = hour + ":" + minue + ":" + sec;
		return timeCount;
	}

	private Handler stepTimeHandler;
	private Runnable mTicker;
	long startTime = 0;
	private Button b;

	// 开始按钮
	public void onClick(View v) {

		String buttonText = b.getText().toString();
		if ("Start".equalsIgnoreCase(buttonText)) {
			b.setText("Stop");
			// 清零 开始计时
			timeTV.setText("00:00:00");
			stepTimeHandler = new Handler();
			startTime = System.currentTimeMillis();
			mTicker = new Runnable() {
				public void run() {
					String content = showTimeCount(System.currentTimeMillis()
							- startTime);
					timeTV.setText(content);

					long now = SystemClock.uptimeMillis();
					long next = now + (1000 - now % 1000);
					stepTimeHandler.postAtTime(mTicker, next);
				}
			};
			// 启动计时线程,定时更新
			mTicker.run();
		} else {
			b.setText("Start");
			// 停止计时 Remove any pending posts of Runnable r that are in the
			// message queue.
			stepTimeHandler.removeCallbacks(mTicker);
		}
	}
}

  

posted @ 2016-06-14 09:58  凤雏小呆  阅读(286)  评论(0编辑  收藏  举报