8

我想用暂停和重启来做倒数计时器。现在我通过实现 ontick() 和 onfinish() 来显示倒数计时器。请帮帮我。这是倒数计时器的代码

final CountDownTimer Counter1 = new CountDownTimer(timervalue1 , 1000)

     {
 public void onTick(long millisUntilFinished)

  {
            System.out.println("onTick method!"(String.valueOf(millisUntilFinished/1000)));long s1=millisUntilFinished;
  }

public void onFinish() 

{
            System.out.println("Finished!");
}

}
4

8 回答 8

19

在 onTick 方法中..保存剩下的毫秒数

   long s1=millisUntilFinished;

当你想暂停定时器使用..

   Counter.cancel();

当你想恢复创建一个新的倒数计时器时,剩下的毫秒数..

 timervalue=s1
  counter= new Counter1();
   counter.start();

看到这个链接

于 2012-04-28T08:55:26.650 回答
3

我会在onTick处理程序中添加一些内容以保存您班级中计时器的进度(剩余毫秒数)。

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

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

请参阅以下链接

关联

关联

于 2012-04-28T08:55:46.613 回答
2

在这种情况下,我使用了两个私有变量:

private long startPauseTime;
private long pauseTime = 0L;

public void pause() { 
    startPauseTime = System.currentTimeMillis(); 
}

public void resumen(){ 
    pauseTime +=  System.currentTimeMillis() - startPauseTime; 
}
于 2012-04-28T09:16:23.043 回答
1

我在stackOverFlow上的第一个答案,希望对您有所帮助:) ...这就是我解决问题的方法,根据您的要求从Fragment,Bottomsheet,Service,Dialog控制计时器,保留一个static boolean变量来控制。

在您的活动中声明:

long presetTime, runningTime;    
Handler mHandler =new Handler();    
Runnable countDownRunnable;
Toast toastObj;
public static boolean shouldTimerRun = true;
TextView counterTv;

在 onCreate 中:

presetTime =60000L;
runningTime= presetTime;
//setting up Timer
countDownRunnable=new Runnable() {
       @Override
         public void run() {
          if (shouldTimerRun) //if false, it runs but skips counting
          {
                counterTv.setText(simplifyTimeInMillis(runningTime));
             if (runningTime==0) {
                 deployToast("Task Completed"); //show toast on task completion 
                }
             runningTime -= 1000;
             presetTime = runningTime; //to resume the timer from last position
          }
          mHandler.postDelayed(countDownRunnable,1000); //simulating on-tick
         }
    };
mHandler.post(countDownRunnable); // Start our CountdownTimer

现在,每当您想暂停计时器时,请更改shouldTimerRun false并恢复 make it 的值true

@Override
    public void onResume() {
        super.onResume();
        shouldTimerRun=true;
    }

    @Override
    public void onPause() {
        super.onPause();
        shouldTimerRun=false;
        deployToast("Timer is paused !!");
    }

帮助方法:(可略过

public static String simplifyTimeInMillis(long time) {

        String result="";
        long difference = time;
        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;

        if (difference<1000){
            return "0";
        }

        if (difference>=3600000) {
            result = result + String.valueOf(difference / hoursInMilli) + "hr ";
            difference = difference % hoursInMilli;
        }
        if (difference>=60000) {
            result = result + String.valueOf(difference / minutesInMilli) + "m ";
            difference = difference % minutesInMilli;
        }
        if (difference>=1000){
            result = result + String.valueOf(difference / secondsInMilli) + "s";
        }

        return result;
    }

public void deployToast(String msg){
        if (toastObj!=null)
            toastObj.cancel();
        toastObj = Toast.makeText(mContext,msg,Toast.LENGTH_SHORT);
        toastObj.show();
    }
于 2017-07-28T17:31:55.297 回答
0

恐怕不可能暂停或停止CountDownTimer,而在 onTick 中暂停或停止对任何用户都没有影响TimerTask

设置TimerTask

class UpdateTimeTask extends TimerTask {
   public void run() {
       long millis = System.currentTimeMillis() - startTime;
       int seconds = (int) (millis / 1000);
       int minutes = seconds / 60;
       seconds     = seconds % 60;

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

}
if(startTime == 0L) {
   startTime = evt.getWhen();
   timer = new Timer();
   timer.schedule(new UpdateTimeTask(), 100, 200);
}

您可以像这样添加事件侦听器..

private Handler mHandler = new Handler();

...

OnClickListener mStartListener = new OnClickListener() {
   public void onClick(View v) {
       if (mStartTime == 0L) {
            mStartTime = System.currentTimeMillis();
            mHandler.removeCallbacks(mUpdateTimeTask);
            mHandler.postDelayed(mUpdateTimeTask, 100);
       }
   }
};

OnClickListener mStopListener = new OnClickListener() {
   public void onClick(View v) {
       mHandler.removeCallbacks(mUpdateTimeTask);
   }
};

有关更多信息,请参阅Android 文档

于 2012-04-28T09:08:20.730 回答
0
//This timer will show min:sec format and can be paused and resumed

public class YourClass extends Activity{
TextView timer;
CountDownTimer ct;
long c = 150000; // 2min:30sec Timer
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.YourXmlLayout);
    timer = (TextView)findViewById(R.id.Yourtimer)
    startTimer(); // it will start the timer

}

public void startTimer(){
ct = new CountDownTimer(c,1000) {
    @Override
    public void onTick(long millisUntilFinished) {
    // Code to show the timer in min:sec form
    // Here timer is a TextView so
    timer.setText(""+String.format("%02d:%02d",millisUntilFinished/60000,(millisUntilFinished/1000)%60));
    c = millisUntilFinished; // it will store millisLeft
    }

    @Override
    public void onFinish() {
        //your code here

    }
};
ct.start();

}
/*===========================================================
*after creating this you can pause this by typing ct.cancel()
*and resume by typing startTimer()*/
于 2015-04-02T07:36:18.597 回答
0
public class MainActivity extends AppCompatActivity {

TextView textView;

CountDownTimer ctimer;
boolean runCountDown;
private long leftTime;
private static final long MILL_IN_FUTURE = 6000;

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

    textView = findViewById(R.id.text_view);
    textView.setText("Click to start");
    textView.setOnClickListener(this::clickStartAndPauseAndResume);
    leftTime = MILL_IN_FUTURE;

}


public void clickStartAndPauseAndResume(View view) {

    if (!runCountDown) {


        long time = (leftTime == 0 || leftTime == MILL_IN_FUTURE) ? MILL_IN_FUTURE : leftTime;
        ctimer = new CountDownTimer(time, 1) {

            @Override
            public void onTick(long l) {

                leftTime = l;
                textView.setText(l + "ms");
            }

            @Override
            public void onFinish() {

                textView.setText("Done");
                leftTime = 0;
                runCountDown = false;
                textView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        textView.setText("Click to start");
                    }
                }, 1000);
            }
        }.start();
        runCountDown = true;
    } else {
        ctimer.cancel();
        textView.setText(textView.getText() + "\n Click to resume");
        runCountDown = false;
    }
 }
}
于 2020-08-23T15:47:50.917 回答
-1

为 CountDownTimer 创建 Pause/Resume 的一种简单而简单的方法是为您的计时器启动、暂停和恢复创建一个单独的方法,如下所示:

public void timerStart(long timeLengthMilli) {
        timer = new CountDownTimer(timeLengthMilli, 1000) {

            @Override
            public void onTick(long milliTillFinish) {
                milliLeft=milliTillFinish;
                min = (milliTillFinish/(1000*60));
                sec = ((milliTillFinish/1000)-min*60);
                clock.setText(Long.toString(min)+":"+Long.toString(sec));
                Log.i("Tick", "Tock");
            }

timerStart 有一个 long 参数,因为它将被下面的 resume() 方法重用。请记住存储您的 milliTillFinished(以上为 milliLeft),以便您可以在 resume() 方法中发送它。暂停和恢复方法分别如下:

public void timerPause() {
        timer.cancel();
    }

    private void timerResume() {
        Log.i("min", Long.toString(min));
        Log.i("Sec", Long.toString(sec));
        timerStart(milliLeft);
    }

这是按钮仅供参考的代码:

startPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(startPause.getText().equals("Start")){
                    Log.i("Started", startPause.getText().toString());
                    startPause.setText("Pause");
                    timerStart(15*1000);
                } else if (startPause.getText().equals("Pause")){
                    Log.i("Paused", startPause.getText().toString());
                    startPause.setText("Resume");
                    timerPause();
                } else if (startPause.getText().equals("Resume")){
                    startPause.setText("Pause");
                    timerResume();
                }
于 2016-08-31T09:25:06.987 回答