Android的:如何暂停和恢复一个倒计时器?计时器、Android

2023-09-04 04:01:10 作者:畢業不想說再見

我已经开发了一个倒计时,我不知道如何暂停和恢复定时器      作为TextView的定时器被点击。单击开始,然后再次单击暂停      以及恢复,再次点击定时器的文本视图。

     

这是我的code:

 定时器=(TextView中)this.findViewById(R.id.time); //定时器
Timer.setOnClickListener(TimerClickListener);
计数器=新mycount的(600000,1000);
创建} //结束

私人OnClickListener TimerClickListener =新OnClickListener(){
公共无效的onClick(视图v){
updateTimeTask(); }

私人无效updateTimeTask(){
如果(决定== 0){
counter.start();
决定= 1;}
否则,如果(判断== 2){
counter.onResume1();
决定= 1; }
其他{
counter.onPause1();
决定= 2; }//万一
}; };

类mycount的扩展CountDownTimer {
公共mycount的(长millisInFuture,长countDownInterval){
超(mil​​lisInFuture,countDownInterval);
} // mycount的
公共无效onResume1(){
onResume(); }
公共无效onPause1(){
的onPause();}
公共无效onFinish(){
Timer.setText(00);
P1 ++;
如果(P1&其中; = 4){
TextView的PScore =(TextView中)findViewById(R.id.pscore);
PScore.setText(P1 +);
}//万一
}//完
公共无效onTick(长millisUntilFinished){
整数milisec =新的整数(双新(millisUntilFinished).intValue());
整数cd_secs = milisec / 1000;

整数分钟=(cd_secs%3600)/ 60;
整数秒=(cd_secs%3600)%60;

Timer.setText(的String.Format(%02D,分)+:
+的String.Format(%02D,秒));
///长的timeleft = millisUntilFinished / 1000;
/} //上打勾
 } //类mycount的

保护无效onResume(){
super.onResume();
//handler.removeCallbacks(updateTimeTask);
//handler.postDelayed(updateTimeTask,1000);
} // onResume

@覆盖
保护无效的onPause(){
super.onPause();
//做的东西
} //的onPause
 

  

任何帮助将是AP preciated。谢谢!

解决方案

  / *
 *版权所有(C)2010安德鲁·盖纳
 *
 * Apache许可证下授权,版本2.0(以下简称许可证);
 *您可能不能使用这个文件除了在遵守许可。
 *您可以在获得许可证的副本
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意,软件
 *许可证下发布分布在原样的基础上,
 *无担保或任何形式的条件,无论是EX preSS或暗示的保证。
 *请参阅许可的特定语言的管理权限和
 *许可下限制。
 * /

//从Android的CountDownTimer类改编

包com.cycleindex.multitimer;

进口android.os.Handler;
进口android.os.Message;
进口android.os.SystemClock;

/ **
 *安排一个倒计时,直到在将来的时间,用
 *沿途间隔定期通知。
 *
  *在调用{@link #onTick(长)}同步到该物体,
 *调用一次{@link #onTick(长)}永远不会发生之前的previous
 *回调完成。这是只有在相关的实施
 * {@link #onTick(长)}花费的时间量来执行是显著
 *相比倒计时间隔。
 * /
公共抽象类CountDownTimerWithPause {

    / **
     *米利斯因为报警时,应停止启动。
     * /
  专用长mStopTimeInFuture;

  / **
   *实时剩余,直到定时器完成
   * /
    专用长mMillisInFuture;

    / **
     *计时器在启动总时间
     * /
    私人最终长mTotalCountdown;

    / **
     *用户收到的回调米利斯的间隔
     * /
    私人最终长mCountdownInterval;

    / **
     *定时器上的剩余时间,当它被暂停,如果目前已暂停;否则为0。
     * /
    专用长mPauseTimeRemaining;

    / **
     *如果真定时器启动运行,否则为false。
     * /
    私人布尔mRunAtStart;

    / **
     * @参数millisInFuture米利斯的数目在将来从呼叫
     *以{@link #START}直至倒计时完成,{@link #onFinish()}
     *被称为
     *参数countDownInterval的时间间隔以millis的,在其中执行
     * {@link #onTick(millisUntilFinished)}回调
     *参数runAtStart真,如果定时器应该开始运行,否则为false
     * /
    公共CountDownTimerWithPause(长millisOnTimer,长countDownInterval,布尔runAtStart){
        mMillisInFuture = millisOnTimer;
        mTotalCountdown = mMillisInFuture;
        mCountdownInterval = countDownInterval;
        mRunAtStart = runAtStart;
    }

    / **
     *取消倒计时,并清除所有其余邮件
     * /
    公众最终无效取消(){
        mHandler.removeMessages(MSG);
    }

    / **
     *创建计时器对象。
     * /
    公共同步最后CountDownTimerWithPause创建(){
        如果(mMillisInFuture&所述; = 0){
            onFinish();
        } 其他 {
          mPauseTimeRemaining = mMillisInFuture;
        }

        如果(mRunAtStart){
          恢复();
        }

        回到这一点;
    }

    / **
     *暂停计数器。
     * /
  公共无效暂停(){
    如果(isRunning()){
      mPauseTimeRemaining =的timeleft();
      取消();
    }
  }

  / **
   *简历柜台。
   * /
  公共无效简历(){
    如果(isPaused得到()){
      mMillisInFuture = mPauseTimeRemaining;
      mStopTimeInFuture = SystemClock.elapsedRealtime()+ mMillisInFuture;
          mHandler.sendMessage(mHandler.obtainMessage(MSG));
      mPauseTimeRemaining = 0;
    }
  }

  / **
   *测试是否计时器暂停。
   * @返回true,如果定时器目前已暂停,否则为false。
   * /
  公共布尔isPaused得到(){
    返回(mPauseTimeRemaining大于0);
  }

  / **
   *测试是否在定时器运行。 (执行逻辑否定{@link #isPaused()})
   * @返回true,如果计时器正在运行,否则为false。
   * /
  公共布尔isRunning(){
    返回(isPaused得到()!);
  }

  / **
   *直到定时器结束返回剩余的毫秒数
   * @返回剩余的毫秒数,直到定时器结束
   * /
  众长的timeleft(){
    长millisUntilFinished;
    如果(isPaused得到()){
      millisUntilFinished = mPauseTimeRemaining;
    } 其他 {
      millisUntilFinished = mStopTimeInFuture  -  SystemClock.elapsedRealtime();
      如果(millisUntilFinished℃,)millisUntilFinished = 0;
    }
    返回millisUntilFinished;
  }

  / **
   *返回在总的毫秒数,该计时器设定为运行
   *毫秒计时器的@return数设定为运行
   * /
  众长totalCountdown(){
    返回mTotalCountdown;
  }

  / **
   *返回已计时器上经过的毫秒数。
   返回:已经经过计时器的毫秒数。
   * /
  众长timePassed(){
    返回mTotalCountdown  - 的timeleft();
  }

  / **
   *如果定时器已经启动,否则为false返回true。
   * @返回true,如果计时器已经启动,否则为false。
   * /
  公共布尔hasBeenStarted(){
    返程(mPauseTimeRemaining< = mMillisInFuture);
  }

    / **
     *回调解雇了固定的间隔
     * @参数millisUntilFinished的时间量,直到完成
     * /
    公共抽象无效onTick(长millisUntilFinished);

    / **
     *回调时激发的时间到了。
     * /
    公共抽象无效onFinish();


    私有静态最终诠释味精= 1;


    //手柄倒计时
    私人处理程序mHandler =新的处理程序(){

        @覆盖
        公共无效的handleMessage(信息MSG){

            同步(CountDownTimerWithPause.this){
                长millisLeft =的timeleft();

                如果(millisLeft&所述; = 0){
                    取消();
                  onFinish();
                }否则如果(millisLeft< mCountdownInterval){
                    //没有打勾,只是推迟,直到做完
                    sendMessageDelayed(obtainMessage(MSG),millisLeft);
                } 其他 {
                    长lastTickStart = SystemClock.elapsedRealtime();
                    onTick(millisLeft);

                    //考虑到用户的onTick服用的时间来执行
                    长延时= mCountdownInterval  - (SystemClock.elapsedRealtime() -  lastTickStart);

                    //特殊情况:用户的onTick比mCountdownInterval了多
                    //完整,跳到下一个时间间隔
                    而(延迟℃下)延迟+ = mCountdownInterval;

                    sendMessageDelayed(obtainMessage(MSG),延迟);
                }
            }
        }
    };
}
 
求一个电脑倒计时器 分 秒的

I have developed a Count Down Timer and I am not sure how to pause and resume the timer as the textview for the timer is being clicked. Click to start then click again to pause and to resume, click again the timer's text view.

This is my code:

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  

Any help would be appreciated. thanks!

解决方案

/*
 * 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);
                }
            }
        }
    };
}