new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start()
这有助于我创建一个计时器,但我怎么能尽快创建一个计时器 上述计时器完成并在计时器时生成通知 饰面
答案 0 :(得分:1)
首先:创建一个扩展CountDownTimer的类
public class SecondTimer extends CountDownTimer{
public SecondTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
//Generate notification here
}
}
第二:初始化该类的实例
SecondTimer secondTimer = new SecondTimer(5000,1000);
第三:当第一个计时器停止时启动SecondTimer
public class FirstTimer extends CountDownTimer{
public SecondTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
secondTimer.start();
}
}
FirstTimer firstTimer = new FirstTimer(5000,1000);
firstTimer.start();
答案 1 :(得分:0)
您不应将CountDownTimer定义为匿名类,而应将其定义在自己的文件中。然后你可以调用:new CountDownTimer(30000,1000)在前一个的onFinish()方法中启动它。通知,你可以。 G。使用Toasts或Snackbars。
答案 2 :(得分:0)
这应该可以正常工作
package com.stackoverflow.example; import android.os.CountDownTimer; /** * @author aminu on 5/7/2016. */ public class CountDownTimerHelper { private int numOfRuns; private long millisInFuture, countDownInterval; private CountDownTimerHelper(int numOfRuns, long millisInFuture, long countDownInterval) { //you may check for invalid arguments here like negative intervals this.numOfRuns = numOfRuns; this.millisInFuture = millisInFuture; this.countDownInterval = countDownInterval; } private void tryRun() { if (numOfRuns-- > 0) { new CountDownTimerImpl(millisInFuture, countDownInterval).start(); } } public static void startCountDownTimers(int numOfRuns, long millisInFuture, long countDownInterval) { new CountDownTimerHelper(numOfRuns, millisInFuture, countDownInterval).tryRun(); } private class CountDownTimerImpl extends CountDownTimer { /** * @param millisInFuture The number of millis in the future from the call * to {@link #start()} until the countdown is done and {@link #onFinish()} * is called. * @param countDownInterval The interval along the way to receive * {@link #onTick(long)} callbacks. */ private CountDownTimerImpl(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { //mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); } @Override public void onFinish() { //notify user countdown ended by showing toast or something like that //mTextField.setText("done " + "remaining " + numOfRuns + "); tryRun(); } } }
然后使用它只需CountDownTimerHelper.startCountDownTimers(numOfRuns,yourDuration,yourInterval)
的例如强>
CountDownTimerHelper.startCountDownTimers(5,15000,1000) //this will run 5 successive countdowntimers with duration 15 seconds and interval 1 second