Pause CountDownTimer in Android when activity is not in front

后端 未结 7 607
旧巷少年郎
旧巷少年郎 2020-12-02 20:43

I have an activity that uses a CountDownTimer that counts down from 10. How do I pause that timer when the activity is no longer in focus, like if the user get a call or som

7条回答
  •  清歌不尽
    2020-12-02 21:12

    You can try using 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();
    
    
            }
        };
    

    Use hourglass.startTimer(); to start the timer.

    It has helper methods which allow to pause and resume the timer.

    hourglass.pauseTimer();
    

    AND

    hourglass.resumeTimer();
    

提交回复
热议问题