首页 > 解决方案 > 在 Android Studio 中的倒数计时器后获取通知

问题描述

我正在Android Studio中为40分钟的倒数计时器构建一个应用程序,我想在时间完成后收到通知,问题是我应该将通知代码放在哪里,以便在倒计时完成后出现。这是我正在尝试的,它在倒计时后发生冲突 public void startTimer() {

    CountDownTimer cdt= new CountDownTimer(60000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            timeLeft = millisUntilFinished;
            updateTimer();
        }

        @Override
        public void onFinish() {
            NewMessageNotification sms = new NewMessageNotification();
            sms.notify();

        }
    };
    cdt.start();
    startBtn.setText("PAUSE");
    timeRunning = true;
}

标签: android-studio

解决方案


该类CountDownTimer有两个回调:onTick(long millisUntilFinished)onFinish(). 第一个定期触发,而第二个在时间到时触发。

因此,如果您希望在时间到时显示通知,则应将您的代码添加到onFinish()您覆盖它的确切位置。

例子:

CountDownTimer cdt = new CountDownTimer(30000, 1000) {

     @override
     public void onTick(long millisUntilFinished) {
         //code for regular intervals or nothing 
     }

     @override
     public void onFinish() {
         //your code for notification
     }
  };

  cdt.start();

它已经完成了


推荐阅读