我无法阻止Android计时器

时间:2016-01-05 22:37:42

标签: android timer

我正在使用以下代码在我的Android应用中运行计时器。

我想在时间到达

时准确停止计时器
  • 1分钟
  • 2分钟
  • 3分钟

等等。 但我无法理解如何做到这一点。 任何帮助将不胜感激。

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView timerTextView;
    long startTime = 0;

    //runs without a timer by reposting this handler at the end of the runnable
    Handler timerHandler = new Handler();
    Runnable timerRunnable = new Runnable() {

        @Override
        public void run() {
            long millis = System.currentTimeMillis() - startTime;
            int seconds = (int) (millis / 1000);
            int minutes = seconds / 60;
            seconds = seconds % 60;

            timerTextView.setText(String.format("%d:%02d", minutes, seconds));

            timerHandler.postDelayed(this, 500);
        }
    };

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

        timerTextView = (TextView) findViewById(R.id.text);

        Button b = (Button) findViewById(R.id.button);
        b.setText("start");
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Button b = (Button) v;
                if (b.getText().equals("stop")) {
                    timerHandler.removeCallbacks(timerRunnable);
                    b.setText("start");
                } else {
                    startTime = System.currentTimeMillis();
                    timerHandler.postDelayed(timerRunnable, 0);
                    b.setText("stop");
                }
            }
        });
    }

  @Override
    public void onPause() {
        super.onPause();
        timerHandler.removeCallbacks(timerRunnable);
        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
    }

}

1 个答案:

答案 0 :(得分:2)

为什么不使用CountDownTimer类?

您可以简单地将其实例化为:

int bigTime = 1000000000;

//1000 is ms after which the timer ticks (that is, the method gets called and so, you can update your view)
CountDownTimer countDownTimer = new CountDownTimer(bigTime, 1000) {
    public void onTick(long millisUntilFinished) {
        updateTime(); 
        //you can write the code to update your view in this method
    }
    @Override
    public void onFinish() {
        Log.i("Get a life bro..."," 31 years have passed!");
    }
};

现在,在onCreate()方法中,根据开始/停止按钮上的clicklisteners,您只需启动或停止计时器:

countDownTimer.start();

if(seconds == 0 && minutes > 0) {
    // get the values of seconds and minutes from the view.
    countDownTimer.cancel();
}

如果您想暂停计时器并从暂停时间开始,您可以存储时间值(以毫秒为单位),停止计时器并在添加存储的值后重新启动计时器。