簡體   English   中英

如何在Android Studio中使用另一個計時器啟動計時器

[英]How to start a timer using another timer in Android Studio

我是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。

這個怎么樣? 我修改了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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM