Java 安卓:如何暂停和恢复倒计时?
我已经开发了一个倒计时计时器,我不知道如何暂停和恢复计时器,因为正在单击计时器的文本视图。单击以开始,然后再次单击以暂停,再次单击计时器的文本视图以继续 这是我的代码:Java 安卓:如何暂停和恢复倒计时?,java,android,onpause,countdowntimer,Java,Android,Onpause,Countdowntimer,我已经开发了一个倒计时计时器,我不知道如何暂停和恢复计时器,因为正在单击计时器的文本视图。单击以开始,然后再次单击以暂停,再次单击计时器的文本视图以继续 这是我的代码: Timer = (TextView) this.findViewById(R.id.time); //TIMER Timer.setOnClickListener(TimerClickListener); counter = new MyCount(600000, 1000); }//end of c
Timer = (TextView) this.findViewById(R.id.time); //TIMER
Timer.setOnClickListener(TimerClickListener);
counter = new MyCount(600000, 1000);
}//end of create
private OnClickListener TimerClickListener = new OnClickListener() {
public void onClick(View v) {
updateTimeTask();
}
private void updateTimeTask() {
if (decision == 0) {
counter.start();
decision = 1;
} else if (decision == 2) {
counter.onResume1();
decision = 1;
} else {
counter.onPause1();
decision = 2;
}//end if
}
;
};
class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}//MyCount
public void onResume1() {
onResume();
}
public void onPause1() {
onPause();
}
public void onFinish() {
Timer.setText("00:00");
p1++;
if (p1 <= 4) {
TextView PScore = (TextView) findViewById(R.id.pscore);
PScore.setText(p1 + "");
}//end if
}//finish
public void onTick(long millisUntilFinished) {
Integer milisec = new Integer(new Double(millisUntilFinished).intValue());
Integer cd_secs = milisec / 1000;
Integer minutes = (cd_secs % 3600) / 60;
Integer seconds = (cd_secs % 3600) % 60;
Timer.setText(String.format("%02d", minutes) + ":"
+ String.format("%02d", seconds));
///long timeLeft = millisUntilFinished / 1000;
/}//on tick
}//class MyCount
protected void onResume() {
super.onResume();
//handler.removeCallbacks(updateTimeTask);
//handler.postDelayed(updateTimeTask, 1000);
}//onResume
@Override
protected void onPause() {
super.onPause();
//do stuff
}//onPause
Timer=(TextView)this.findViewById(R.id.time)//计时器
Timer.setOnClickListener(TimerClickListener);
计数器=新的MyCount(600000,1000);
}//创建结束
private OnClickListener TimerClickListener=new OnClickListener(){
公共void onClick(视图v){
updateTimeTask();
}
私有void updateTimeTask(){
如果(决策==0){
counter.start();
决策=1;
}否则如果(决策==2){
计数器onResume1();
决策=1;
}否则{
counter.onPause1();
决策=2;
}//如果结束
}
;
};
类MyCount扩展了倒计时{
公共MyCount(长百万未来,长倒计时间隔){
超级(毫秒未来,倒计时间隔);
}//我的帐户
在简历1()上公开作废{
onResume();
}
public void onPause1(){
onPause();
}
公共无效onFinish(){
Timer.setText(“00:00”);
p1++;
如果(p1没有API来暂停或恢复它。您应该做的是cancel()
定时器并将剩余时间存储在变量中。当再次点击恢复按钮时,使用变量中的值重新启动定时器
您知道您可能感兴趣。/*
/*
* Copyright (C) 2010 Andrew Gainer
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Adapted from Android's CountDownTimer class
package com.cycleindex.multitimer;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
/**
* Schedule a countdown until a time in the future, with
* regular notifications on intervals along the way.
*
* The calls to {@link #onTick(long)} are synchronized to this object so that
* one call to {@link #onTick(long)} won't ever occur before the previous
* callback is complete. This is only relevant when the implementation of
* {@link #onTick(long)} takes an amount of time to execute that is significant
* compared to the countdown interval.
*/
public abstract class CountDownTimerWithPause {
/**
* Millis since boot when alarm should stop.
*/
private long mStopTimeInFuture;
/**
* Real time remaining until timer completes
*/
private long mMillisInFuture;
/**
* Total time on timer at start
*/
private final long mTotalCountdown;
/**
* The interval in millis that the user receives callbacks
*/
private final long mCountdownInterval;
/**
* The time remaining on the timer when it was paused, if it is currently paused; 0 otherwise.
*/
private long mPauseTimeRemaining;
/**
* True if timer was started running, false if not.
*/
private boolean mRunAtStart;
/**
* @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 in millis at which to execute
* {@link #onTick(millisUntilFinished)} callbacks
* @param runAtStart True if timer should start running, false if not
*/
public CountDownTimerWithPause(long millisOnTimer, long countDownInterval, boolean runAtStart) {
mMillisInFuture = millisOnTimer;
mTotalCountdown = mMillisInFuture;
mCountdownInterval = countDownInterval;
mRunAtStart = runAtStart;
}
/**
* Cancel the countdown and clears all remaining messages
*/
public final void cancel() {
mHandler.removeMessages(MSG);
}
/**
* Create the timer object.
*/
public synchronized final CountDownTimerWithPause create() {
if (mMillisInFuture <= 0) {
onFinish();
} else {
mPauseTimeRemaining = mMillisInFuture;
}
if (mRunAtStart) {
resume();
}
return this;
}
/**
* Pauses the counter.
*/
public void pause () {
if (isRunning()) {
mPauseTimeRemaining = timeLeft();
cancel();
}
}
/**
* Resumes the counter.
*/
public void resume () {
if (isPaused()) {
mMillisInFuture = mPauseTimeRemaining;
mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
mHandler.sendMessage(mHandler.obtainMessage(MSG));
mPauseTimeRemaining = 0;
}
}
/**
* Tests whether the timer is paused.
* @return true if the timer is currently paused, false otherwise.
*/
public boolean isPaused () {
return (mPauseTimeRemaining > 0);
}
/**
* Tests whether the timer is running. (Performs logical negation on {@link #isPaused()})
* @return true if the timer is currently running, false otherwise.
*/
public boolean isRunning() {
return (! isPaused());
}
/**
* Returns the number of milliseconds remaining until the timer is finished
* @return number of milliseconds remaining until the timer is finished
*/
public long timeLeft() {
long millisUntilFinished;
if (isPaused()) {
millisUntilFinished = mPauseTimeRemaining;
} else {
millisUntilFinished = mStopTimeInFuture - SystemClock.elapsedRealtime();
if (millisUntilFinished < 0) millisUntilFinished = 0;
}
return millisUntilFinished;
}
/**
* Returns the number of milliseconds in total that the timer was set to run
* @return number of milliseconds timer was set to run
*/
public long totalCountdown() {
return mTotalCountdown;
}
/**
* Returns the number of milliseconds that have elapsed on the timer.
* @return the number of milliseconds that have elapsed on the timer.
*/
public long timePassed() {
return mTotalCountdown - timeLeft();
}
/**
* Returns true if the timer has been started, false otherwise.
* @return true if the timer has been started, false otherwise.
*/
public boolean hasBeenStarted() {
return (mPauseTimeRemaining <= mMillisInFuture);
}
/**
* Callback fired on regular interval
* @param millisUntilFinished The amount of time until finished
*/
public abstract void onTick(long millisUntilFinished);
/**
* Callback fired when the time is up.
*/
public abstract void onFinish();
private static final int MSG = 1;
// handles counting down
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
synchronized (CountDownTimerWithPause.this) {
long millisLeft = timeLeft();
if (millisLeft <= 0) {
cancel();
onFinish();
} else if (millisLeft < mCountdownInterval) {
// no tick, just delay until done
sendMessageDelayed(obtainMessage(MSG), millisLeft);
} else {
long lastTickStart = SystemClock.elapsedRealtime();
onTick(millisLeft);
// take into account user's onTick taking time to execute
long delay = mCountdownInterval - (SystemClock.elapsedRealtime() - lastTickStart);
// special case: user's onTick took more than mCountdownInterval to
// complete, skip to next interval
while (delay < 0) delay += mCountdownInterval;
sendMessageDelayed(obtainMessage(MSG), delay);
}
}
}
};
}
*版权所有(C)2010年安德鲁·盖纳
*
*根据Apache许可证2.0版(以下简称“许可证”)获得许可;
*除非遵守许可证,否则不得使用此文件。
*您可以通过以下方式获得许可证副本:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*除非适用法律要求或书面同意,软件
*根据许可证进行的分发是按“原样”进行分发的,
*无任何明示或暗示的保证或条件。
*请参阅许可证以了解管理权限和权限的特定语言
*许可证下的限制。
*/
//改编自Android的倒计时类
包com.cycleindex.multitimer;
导入android.os.Handler;
导入android.os.Message;
导入android.os.SystemClock;
/**
*安排倒计时,直到将来某个时间
*沿途定期通知。
*
*对{@link#onTick(long)}的调用与此对象同步,以便
*对{@link#onTick(long)}的一次调用在前一次调用之前不会发生
*回调已完成。这仅在
*{@link#onTick(long)}需要花费大量时间来执行这项重要任务
*与倒计时间隔相比。
*/
公共抽象类CountDownTimerWithPause{
/**
*当警报停止时,自启动起毫秒。
*/
私人长期信息;
/**
*计时器完成前的实时剩余时间
*/
私人长远规划;
/**
*启动时计时器上的总时间
*/
私人最终长期MTOTALCOUNDOWN;
/**
*用户接收回调的间隔(毫秒)
*/
私人最终长时间间隔;
/**
*计时器暂停时的剩余时间(如果当前已暂停);否则为0。
*/
私人长时间剩余;
/**
*如果计时器开始运行,则为True,否则为false。
*/
私有布尔启动;
/**
*@param millisInFuture未来呼叫的毫秒数
*到{@link#start}直到倒计时结束{@link#onFinish()}
*被称为
*@param countDownInterval以毫秒为单位的执行间隔
*{@link#onTick(millisuntillfinished)}回调
*@param runAtStart如果计时器应该开始运行,则为True,否则为false
*/
带暂停的公共倒计时(长毫秒计时器、长倒计时间隔、布尔运行开始){
mMillisInFuture=毫秒计时器;
MTOTALCOUNTTOWN=mmillinfuture;
mCountdownInterval=倒计时间隔;
mRunAtStart=runAtStart;
}
/**
*取消倒计时并清除所有剩余的消息
*/
公开最终作废取消(){
mHandler.removeMessages(MSG);
}
/**
*创建计时器对象。
*/
公共同步最终倒计时带暂停创建(){
if(mmillisfuture 0);
}
/**
*测试计时器是否正在运行。(对{@link#isPaused()}执行逻辑求反)
*@如果计时器当前正在运行,则返回true,否则返回false。
*/
公共布尔值正在运行(){
返回(!isPaused());
}
/**
*返回计时器完成前剩余的毫秒数
*@返回计时器完成前剩余的毫秒数
*/
公共长时间限制(){
长毫微光整;
if(isPaused()){
毫秒直至完成=剩余MPauseTime;
}否则{
millisUntilFinished=mStopTimeInFuture-SystemClock.elapsedRealtime();
如果(millisUntilFinished<0)millisUntilFinished=0;
}
返回毫秒,直到完成;
}
/**
*返回计时器设置为运行的总毫秒数
*@返回毫秒数计时器已设置为运行
*/
公众长时间倒计时(){
返回mTotalCountdown;
}
/**
*返回计时器上经过的毫秒数。
*@返回计时器上已过的毫秒数。
*/
公共长期通行证(){
返回mTotalCountdown-timeLeft();
}
/**
*如果计时器已启动,则返回true,否则返回false。
*@如果计时器已启动,则返回true,否则返回false。
*/
公共布尔值hasBeenStarted(){
return(mPauseTimeRemaining为您的倒计时器创建暂停/恢复的一个简单的好方法是cre
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");
}
}
timer.start();
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();
}
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();
}
};
hourglass.pauseTimer();
hourglass.resumeTimer();
public static void setTimerMillis(Context context, long millis)
{ SharedPreferences sp =
context.getSharedPreferences(SessionManager.FILE_USER, Context.MODE_PRIVATE);
SharedPreferences.Editor spe = sp.edit(); spe.putLong(SessionManager.TIMER_MILLIS, millis); spe.apply(); }
void setExamTimer() {
setTimerColors();
final long maxTimeToShow = 60000; //testing
final long lastTimeinMillisLeftSaved = TestyBookHelper.getTimerMillis(context); //take saved value from sharedpref
final long intervalTime = 1000;
donut_exam_timer.setMax((int) maxTimeToShow);
CountDownTimer countDownTimer = new CountDownTimer(lastTimeinMillisLeftSaved, intervalTime) {
@Override
public void onTick(long millis) {
TestyBookHelper.setTimerMillis(context, millis);
String hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))); System.out.println(hms);
donut_exam_timer.setText(hms);
donut_exam_timer.setProgress(millis);
}
@Override
public void onFinish() {
}
};
countDownTimer.start();
}
public static long getTimerMillis(Context context) {
SharedPreferences sp = context.getSharedPreferences(SessionManager.FILE_USER, Context.MODE_PRIVATE);
return sp.getLong(SessionManager.TIMER_MILLIS, 60000L);}
@BindView(R.id.play_btn) ImageButton play;
@BindView(R.id.pause_btn) ImageButton pause;
@BindView(R.id.close_btn) ImageButton close;
@BindView(R.id.time) TextView time;
private CountDownTimer countDownTimer;
private long currentMillis=10;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
ButterKnife.bind(this);
}
@OnClick(R.id.play_btn) void play_game(){
this.play();
}
@OnClick(R.id.pause_btn) void pause_game(){
this.pause();
}
@OnClick(R.id.close_btn) void close_game(){
this.close();
}
void play(){
play.setVisibility(View.GONE);
close.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
time.setText(""+currentMillis);
countDownTimer = new CountDownTimer(currentMillis*1000,1000) {
@Override
public void onTick(long millisUntilFinish) {
currentMillis=millisUntilFinish/1000;
time.setText(""+millisUntilFinish/1000);
}
@Override
public void onFinish() {
time.setText("Done!");
}
};
countDownTimer.start();
}
void pause(){
play.setVisibility(View.VISIBLE);
close.setVisibility(View.VISIBLE);
pause.setVisibility(View.GONE);
countDownTimer.cancel();
}
void close(){
if(countDownTimer!=null){
countDownTimer.cancel();
countDownTimer=null;
}
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
class GameActivity : Activity() {
private var timer = CustomTimer(30000, 1000) // 30 seconds duration at 1 second interval
override fun onCreate(savedInstanceState: Bundle?) {
...
timer.onTick = { millisUntilFinished ->
textView.text = "seconds remaining: " + millisUntilFinished / 1000
}
timer.onFinish = {
TODO("do something here")
}
}
override fun onResume() {
super.onResume()
timer.resume()
}
override fun onPause() {
super.onPause()
timer.pause()
}
}