如何使用Android Studio中的另一个计时器启动计时器

时间:2016-11-02 21:30:03

标签: java android timer

我是Java的新手(不到3个月的经验),对于我一直在研究的项目,我需要创建一个计时器。 我以前做过这个,但是我不知道怎么做一件事。

我想在第二个计时器结束时启动计时器。我的意思是,不是使用开始/停止按钮来启动计时器,我想要第二个计时器(从3秒开始)确定第一个计时器何时启动。例如,如果第一个计时器是30秒,它将在第二个计时器从3-0完成倒计时开始倒计时。

我知道必须有其他类或方法/监听器才能做到这一点,但正如我之前所说,这是我第一次使用Java(我通常使用C ++)。

任何关于如何实现这一目标的帮助/指导/代码都会很棒。这是我试图实现这一目标的代码。

爪哇

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button; 
import android.widget.TextView;
import android.os.CountDownTimer;

public class Timer extends AppCompatActivity
{
TextView timer;
TextView timerStart;
Button multi;
int track;
int seconds;
CountDownTimer countDownTimer;
CountDownTimer start;

View.OnClickListener btnListen = new View.OnClickListener(){
    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.multi : start();
                break;
        }
    }

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_timer);
    timer = (TextView) findViewById(R.id.timer);
    timerStart = (TextView) findViewById(R.id.timerStart);
    multi = (Button) findViewById(R.id.multi);
    multi.setOnClickListener(btnListen);

    multi.setText("Start");
}

public void start_timer()
{
    track = 3;
    start = new CountDownTimer(3*1000,1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            timerStart.setText("" + millisUntilFinished / 1000);
        }

        @Override
        public void onFinish() {
            timerStart.setText("Begin");
            track = 0;
        }
    }.start();
    seconds = 30;
    if (timerStart.getText().equals("Begin"))
    {
        start.cancel();
        countDownTimer = new CountDownTimer(30 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timer.setText("" + millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                timer.setText("BEEP");
            }
        }.start();
    }
    else
    {
        System.out.println("Nothing");
    }
}
public void start()
{
    start_timer();
    /*seconds = 30;
    if (timerStart.getText().equals("Begin"))
    {
        countDownTimer = new CountDownTimer(seconds * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                timer.setText("" + millisUntilFinished / 1000);
            }

            @Override
            public void onFinish() {
                timer.setText("BEEP");
            }
        }.start();
    }*/

}
}

同样,这只是我正在玩的东西。如果有不同的方法(比如使用Runnable或Handler),那么我对它持开放态度。我的目标是学习Java。

1 个答案:

答案 0 :(得分:1)

这个怎么样?我修改了CountDownTimer以使其能够被链接。

 public abstract class ChainedCountDownTimer {

    /**
     * Millis since epoch when alarm should stop.
     */
    private final long mMillisInFuture;

    /**
     * The interval in millis that the user receives callbacks
     */
    private final long mCountdownInterval;

    private long mStopTimeInFuture;

    /**
     * boolean representing if the timer was cancelled
     */
    private boolean mCancelled = false;

    /**
     * First timer in chaining
     */
    private ChainedCountDownTimer first;

    /**
     * Next timer
     */
    private ChainedCountDownTimer next;

    /**
     * @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.
     */
    public ChainedCountDownTimer(long millisInFuture, long countDownInterval) {
        mMillisInFuture = millisInFuture;
        mCountdownInterval = countDownInterval;
        first = this;
    }

    /**
     * Cancel the countdown.
     */
    public synchronized final void cancel() {
        first.mCancelled = true;
        mHandler.removeMessages(MSG);
    }

    public void start() {
        first.startInternal();
    }

    /**
     * Start the countdown.
     */
    public synchronized final ChainedCountDownTimer startInternal() {
        mCancelled = false;
        if (mMillisInFuture <= 0) {
            onFinish();

            if (next != null) {
                next.startInternal();
            }

            return this;
        }
        mStopTimeInFuture = SystemClock.elapsedRealtime() + mMillisInFuture;
        mHandler.sendMessage(mHandler.obtainMessage(MSG));
        return this;
    }


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

    public ChainedCountDownTimer setNext(ChainedCountDownTimer next) {
        this.next = next;
        next.first = this.first;

        return this.next;
    }

    private static final int MSG = 1;


    // handles counting down
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            synchronized (ChainedCountDownTimer.this) {
                if (first.mCancelled) {
                    return;
                }

                final long millisLeft = mStopTimeInFuture - SystemClock.elapsedRealtime();

                if (millisLeft <= 0) {
                    onFinish();

                    if (next != null) {
                        next.startInternal();
                    }

                } 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 = lastTickStart + mCountdownInterval - SystemClock.elapsedRealtime();

                    // special case: user's onTick took more than interval to
                    // complete, skip to next interval
                    while (delay < 0) delay += mCountdownInterval;

                    sendMessageDelayed(obtainMessage(MSG), delay);
                }
            }
        }
    };
}

你可以这样使用它。

ChainedCountDownTimer timer1 = new ChainedCountDownTimer(3 * 1000, 1000) {
    @Override
    public void onTick(long millisUntilFinished) {
        Log.d(TAG, "timer1 onTick");
    }

    @Override
    public void onFinish() {
        Log.d(TAG, "timer1 onFinish");
    }
};

ChainedCountDownTimer timer2 = new ChainedCountDownTimer(30 * 1000, 1000) {
    @Override
    public void onTick(long millisUntilFinished) {
        Log.d(TAG, "timer2 onTick");
    }

    @Override
    public void onFinish() {
        Log.d(TAG, "timer2 onFinish");
    }
};

timer1.setNext(timer2).start();