Android 具有暂停和恢复功能的倒数计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10362014/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Countdown timer with pause and resume
提问by Vijaya
I want to do countdown timer with pause and restart.Now i am displaying countdown timer By implenting ontick() and onfinish().please help me out.HEre is th code for countdown timer
我想用暂停和重启来做倒数计时器。现在我正在显示倒数计时器通过实施 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!");
}
}
回答by 5hssba
in onTick method..save the milliseconds left
在 onTick 方法中..保存剩余的毫秒数
long s1=millisUntilFinished;
when you want to pause the timer use..
当你想暂停定时器使用..
Counter.cancel();
when you want to resume create a new countdowntimer with left milliseconds..
当你想恢复创建一个新的倒数计时器时,剩下的毫秒..
timervalue=s1
counter= new Counter1();
counter.start();
回答by Shankar Agarwal
I would add something to the onTick
handler to save the progress of the timer in your class (number of milliseconds left).
我会向onTick
处理程序添加一些内容以保存类中计时器的进度(剩余毫秒数)。
In the onPause()
method for the activity call cancel()
on the timer.
在计时器上的onPause()
活动调用方法中cancel()
。
In the onResume()
method for the activity create a new timer with the saved number of milliseconds left.
在onResume()
活动的方法中创建一个新的计时器,并保留剩余的毫秒数。
Refer the below links
请参考以下链接
回答by Jimmy Collazos
I'm using two private vars in this case:
在这种情况下,我使用了两个私有变量:
private long startPauseTime;
private long pauseTime = 0L;
public void pause() {
startPauseTime = System.currentTimeMillis();
}
public void resumen(){
pauseTime += System.currentTimeMillis() - startPauseTime;
}
回答by Vishal Sharma
My first answer on stackOverFlow, hope it should help :) ...
This is how I solved the problem, control timer from Fragment, Bottomsheet, Service, Dialog as per your requirement, keep a static boolean
variable to control.
我在 stackOverFlow 上的第一个答案,希望它会有所帮助:) ...这就是我解决问题的方法,根据您的要求从 Fragment、Bottomsheet、Service、Dialog 控制计时器,保留一个static boolean
变量进行控制。
declare in your Activity:
在您的活动中声明:
long presetTime, runningTime;
Handler mHandler =new Handler();
Runnable countDownRunnable;
Toast toastObj;
public static boolean shouldTimerRun = true;
TextView counterTv;
In onCreate:
在 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
Now, whenever you want to pause the timer change the value of shouldTimerRun
false
and to resume make it true
.
现在,每当您想暂停计时器时,请更改 的值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 !!");
}
Helping methods: (can be skipped)
求助方法:(可跳过)
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();
}
回答by Rana Shahid
//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()*/
回答by Arif Nadeem
I am afraid that it is not possible to pause or stop CountDownTimer
and pausing or stopping in onTick has no effect whatsoever user TimerTask
instead.
恐怕无法暂停或停止,CountDownTimer
并且在 onTick 中暂停或停止对任何用户都没有影响TimerTask
。
Set up the 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);
}
You can add event listener's like this..
您可以像这样添加事件侦听器..
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);
}
};
For more refer to Android Documentation.
有关更多信息,请参阅Android 文档。
回答by Josh
A nice and simple way to create a Pause/Resume for your CountDownTimer is to create a separate method for your timer start, pause and resume as follows:
为您的 CountDownTimer 创建暂停/恢复的一种很好且简单的方法是为您的计时器启动、暂停和恢复创建一个单独的方法,如下所示:
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");
}
The timerStart has a long parameter as it will be reused by the resume() method below. Remember to store your milliTillFinished (above as milliLeft) so that you may send it through in your resume() method. Pause and resume methods below respectively:
timerStart 有一个长参数,因为它将被下面的 resume() 方法重用。请记住存储您的 millTillFinished (以上为milliLeft),以便您可以在您的 resume() 方法中发送它。暂停和恢复方法分别如下:
public void timerPause() {
timer.cancel();
}
private void timerResume() {
Log.i("min", Long.toString(min));
Log.i("Sec", Long.toString(sec));
timerStart(milliLeft);
}
Here is the code for the button FYI:
这是按钮仅供参考的代码:
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();
}