当活动不在前面时,在Android中暂停CountDownTimer

时间:2011-04-21 00:59:39

标签: android timer

我有一个使用从10开始倒计时的CountDownTimer的活动。当活动不再处于焦点时如何暂停该计时器,如用户接到电话或其他内容,然后在用户进入时恢复计时器回到活动?这甚至可能吗?

7 个答案:

答案 0 :(得分:30)

我会在onTick处理程序中添加一些东西来保存你班级中计时器的进度(剩下的毫秒数)。

在onPause()方法中,定时器上的活动调用cancel()。

在活动的onResume()方法中创建一个新的计时器,并保留剩余的毫秒数。

答案 1 :(得分:25)

您可以使用pause()暂停计时器,然后通过调用start()来启动或恢复countDownTimer。

/**
 * This class uses the native CountDownTimer to 
 * create a timer which could be paused and then
 * started again from the previous point. You can 
 * provide implementation for onTick() and onFinish()
 * then use it in your projects.
 */
public abstract class CountDownTimerPausable {
    long millisInFuture = 0;
    long countDownInterval = 0;
    long millisRemaining =  0;

    CountDownTimer countDownTimer = null;

    boolean isPaused = true;

    public CountDownTimerPausable(long millisInFuture, long countDownInterval) {
        super();
        this.millisInFuture = millisInFuture;
        this.countDownInterval = countDownInterval;
        this.millisRemaining = this.millisInFuture;
    }
    private void createCountDownTimer(){
        countDownTimer = new CountDownTimer(millisRemaining,countDownInterval) {

            @Override
            public void onTick(long millisUntilFinished) {
                millisRemaining = millisUntilFinished;
                CountDownTimerPausable.this.onTick(millisUntilFinished);

            }

            @Override
            public void onFinish() {
                CountDownTimerPausable.this.onFinish();

            }
        };
    }
    /**
     * Callback fired on regular interval.
     * 
     * @param millisUntilFinished The amount of time until finished. 
     */
    public abstract void onTick(long millisUntilFinished);
    /**
     * Callback fired when the time is up. 
     */
    public abstract void onFinish();
    /**
     * Cancel the countdown.
     */
    public final void cancel(){
        if(countDownTimer!=null){
            countDownTimer.cancel();
        }
        this.millisRemaining = 0;
    }
    /**
     * Start or Resume the countdown. 
     * @return CountDownTimerPausable current instance
     */
    public synchronized final CountDownTimerPausable start(){
        if(isPaused){
            createCountDownTimer();
            countDownTimer.start();
            isPaused = false;
        }
        return this;
    }
    /**
     * Pauses the CountDownTimerPausable, so it could be resumed(start)
     * later from the same point where it was paused.
     */
    public void pause()throws IllegalStateException{
        if(isPaused==false){
            countDownTimer.cancel();
        } else{
            throw new IllegalStateException("CountDownTimerPausable is already in pause state, start counter before pausing it.");
        }
        isPaused = true;
    }
    public boolean isPaused() {
        return isPaused;
    }
}

答案 2 :(得分:17)

无需创建新的Timer,只需设置millisUntilFinished = total即可。例如

private CountDownTimer cdTimer;
private long total = 30000;

        ...
        toggleButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view){
                if(toggleButton.isChecked()) {
                    startCountDownTimer();
                }else{
                    cdTimer.cancel();
                }
            }
        });
        ...

    private void startCountDownTimer() {
        cdTimer = new CountDownTimer(total, 1000) {
            public void onTick(long millisUntilFinished) {
                //update total with the remaining time left
                total = millisUntilFinished;
                nTimeLabel.setText("seconds remaining: " +  millisUntilFinished/ 1000);
            }
            public void onFinish() {
                nTimeLabel.setText("done!");
            }
        }.start();
    }

答案 3 :(得分:1)

这一定正是您正在寻找的。来源是this Gist.

primRoots

答案 4 :(得分:1)

您可以尝试使用Hourglass

Hourglass hourglass = new Hourglass(50000, 1000) {
        @Override
        public void onTimerTick(long timeRemaining) {
            // Update UI
            Toast.show(MainActivity.this, String.valueOf(timeRemaining), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onTimerFinish() {
            // Timer finished
            Toast.show(MainActivity.this, "Timer finished", Toast.LENGTH_SHORT).show();


        }
    };

使用hourglass.startTimer();启动计时器。

它有辅助方法,可以暂停和恢复计时器。

hourglass.pauseTimer();

hourglass.resumeTimer();

答案 5 :(得分:0)

这是下面的代码。在您的活动中使用它可以正常工作。

public class MainActivity extends AppCompatActivity {

    TextView textview;
    final static long INTERVAL = 1000;
    final static long TIMEOUT = 11000;
    static long millisecondsleft;
    boolean isPause =false;

    CountDownTimer countDownTimer;
    CountDownTimer countDownTimeronResume;

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

        textview=findViewById(R.id.textviewcheck);
 }

    @Override
    protected void onResume() {
        super.onResume();

       if(isPause == false) {
           countDownTimer = new CountDownTimer(TIMEOUT, INTERVAL) {
               @Override
               public void onTick(long millisUntilFinished) {
                   millisecondsleft = millisUntilFinished;
                   textview.setText(":" + String.format("%02d", millisUntilFinished / 1000));
               }

               @Override
               public void onFinish() {

                   textview.setText("DONE!");
               }
           }.start();

       } else{
                     countDownTimeronResume = new CountDownTimer(millisecondsleft, INTERVAL) {
                       @Override
                       public void onTick(long millisUntilFinished) {
                           Toast.makeText(MainActivity.this, "ONPAUSED", Toast.LENGTH_SHORT).show();
                           millisecondsleft = millisUntilFinished;
                           textview.setText(":" + String.format("%02d", millisUntilFinished / 1000));
                       }

                       @Override
                       public void onFinish() {
                           textview.setText("DONE!");

                       }
                   }.start();
         }


    }

    @Override
    protected void onPause() {
        super.onPause();

        if(countDownTimer!=null){
            countDownTimer.cancel();
            isPause = true;
        }
       if(countDownTimeronResume!=null){
            countDownTimeronResume.cancel();
       }
    }
}

答案 6 :(得分:0)

对于Kotlin用户,结帐this

例如:

// Init timer
lateinit var timerExt: CountDownTimerExt

timerExt = object : CountDownTimerExt(TIMER_DURATION, TIMER_INTERVAL) {
    override fun onTimerTick(millisUntilFinished: Long) {
        Log.d("MainActivity", "onTimerTick $millisUntilFinished")
    }

    override fun onTimerFinish() {
        Log.d("MainActivity", "onTimerFinish")
    }

}

// Start/Resume timer
timerExt.start()

// Pause timer
timerExt.pause()

// Restart timer
timerExt.restart()