1

I need a count up timer in my application. I browsed many forums about this subject, but I could not find anything. Actually I understood we can do this with chronometer, but I have 2 problem with chronometer:

  1. I cannot using chronometer in Service because chronometer needs a layout.
  2. I cannot initialize chronometer to count more than 1 hour.

My code is here:

stopWatch =  new Chronometer (MainActivity.this);
startTime = SystemClock.elapsedRealtime();
stopWatch.start();
stopWatch.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
    @Override
    public void onChronometerTick(Chronometer arg0) {
        countUp = (SystemClock.elapsedRealtime() - arg0.getBase()) / 1000;
        String asText = (countUp / 60) + ":" + (countUp % 60);
        Log.i("t", asText);
    }
});
Rambod Ghasemi
  • 51
  • 1
  • 2
  • 11
  • Can you be more specific than "I need count up timer"? How do you intend to use this timer? This information may help us to suggest other mechanisms or approaches. – EJK Jan 28 '16 at 14:38
  • How about using a `CountDownTimer` in the reverse? – Uma Kanth Jan 28 '16 at 14:43
  • @UmaKanth maybe help me can you tell me how to do this? – Rambod Ghasemi Jan 28 '16 at 14:54
  • This class is documented at http://developer.android.com/reference/android/os/CountDownTimer.html. Perhaps you should start by reading the documentation. – EJK Jan 28 '16 at 14:56

4 Answers4

12

You can use a countDownTimer in reverse and get the time elapsed.

long totalSeconds = 30;
long intervalSeconds = 1;

CountDownTimer timer = new CountDownTimer(totalSeconds * 1000, intervalSeconds * 1000) {

    public void onTick(long millisUntilFinished) {
        Log.d("seconds elapsed: " , (totalSeconds * 1000 - millisUntilFinished) / 1000);
    }

    public void onFinish() {
        Log.d( "done!", "Time's up!");
    }

};

To start the timer.

timer.start();

To stop the timer.

timer.cancel();
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
  • Here's the [documentation](http://developer.android.com/intl/zh-tw/reference/android/os/CountDownTimer.html). In short, It will run the onTick function for every time intervalSeconds elapsed untill totalSeconds are done. Everything is in millis and hence the multiplication by 1000. – Uma Kanth Jan 28 '16 at 15:53
  • thanks i have one question : i cant stop count down(up) with countdown.cancel() it does not need to create another one question... :D – Rambod Ghasemi Jan 28 '16 at 15:59
  • You will need to create a CountDownTImer object. I updated my answer. – Uma Kanth Jan 28 '16 at 16:01
2

The sec,min and hr increments everytime the values hit 59,59,23 respectively. Each values are displayed in different views creating a digital stopwatch.

checkin.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(final View view) {
    checkin.setEnabled(false);
            new CountDownTimer(300000000, 1000){
                public void onTick(long millisUntilFinished){

                    sec++;
                    if(sec==59) {
                        min++;
                        sec=0;
                    }
                    if(min==59){
                        min=0;
                        hr++;
                    }
                    if(hr==23){
                        hr=00;
                    }
                    secView.setText(String.valueOf(sec));
                    minView.setText(String.valueOf(min));
                    hrView.setText(String.valueOf(hr));
                }
                public void onFinish(){
                    Snackbar.make(view, "Finish", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            }.start();
        }
    });
reflexgravity
  • 910
  • 10
  • 17
  • Please explain your code and why it helps answering the question. Maybe reading [this](https://stackoverflow.com/help/how-to-answer) will help understanding what a good answer is. – Markus Aug 06 '17 at 17:30
  • What it basically does is. Every time the second hits 59 it increases the minute and every time the minute hits 59 it increases the hour. The countdown timer has given a limit from 1s to a random maximum no. – reflexgravity Aug 07 '17 at 17:50
2

Using RxJava, you can write

Disposable var = Observable
            .interval(1, TimeUnit.SECONDS)
            .subscribe(
                    time -> {
                        long minutes = time / 60;
                        long second = time % 60;
                        timer.setText("" + minutes + ":" + second);
                    });

you can stop the timer by using var.dispose()

mchouhan_google
  • 1,775
  • 1
  • 20
  • 28
-1

You can use this code to do so: https://gist.github.com/MiguelLavigne/8809180c5b8fe2fc7403

/**
 * Simple timer class which count up until stopped.
 * Inspired by {@link android.os.CountDownTimer}
 */
public abstract class CountUpTimer {

    private final long interval;
    private long base;

    public CountUpTimer(long interval) {
        this.interval = interval;
    }

    public void start() {
        base = SystemClock.elapsedRealtime();
        handler.sendMessage(handler.obtainMessage(MSG));
    }

    public void stop() {
        handler.removeMessages(MSG);
    }

    public void reset() {
        synchronized (this) {
            base = SystemClock.elapsedRealtime();
        }
    }

    abstract public void onTick(long elapsedTime);

    private static final int MSG = 1;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            synchronized (CountUpTimer.this) {
                long elapsedTime = SystemClock.elapsedRealtime() - base;
                onTick(elapsedTime);
                sendMessageDelayed(obtainMessage(MSG), interval);
            }
        }
    };
}
Shalev Moyal
  • 644
  • 5
  • 12