4

I'm new in Android programming but i know Java. My question is, how does a timer work in Android? I've read that is better to use a handler. What I want to do is, you click a button and the timer starts. To the moment when the button is clicked all is clear for me but how to start the timer?

Bond
  • 16,071
  • 6
  • 30
  • 53
Phil
  • 304
  • 1
  • 5
  • 12
  • Welcome to Stack Overflow. Read this so your things don't get downvoted to oblivion: http://stackoverflow.com/help/how-to-ask – Noobification Jul 26 '15 at 19:28

1 Answers1

6

How does a timer work in Android?

You better read Timer documentation, CountDownTimer Documentation and Handler Documentation.

To the moment, when the button is clicked, all is cleared for me; but, how can I start the timer?

If I didn't misunderstand your question, when you say Timer, you refer to CounteDownTimer. So, you should have something like this:

(I've written a sample code. So, you should understand it first, and then, you should apply it to your code.)

Adding the Buttons

btn1 = (Button)findViewById(R.id.bt1);
btn2 = (Button)findViewById(R.id.bt2);

Adding the SetOnClickListener()

btn1.setOnClickListener(new OnClickListener() {
    @Override
        public void onClick(View arg0) {

    });
}

btn2.setOnClickListener(new OnClickListener() {
    @Override
        public void onClick(View arg0) {

    });
}

My btn1 starts the CountDownTimer, and the second one stops and clears it.

Now, I create an Inner Class with CountDownTimerTest name.

public class CountDownTimerTest extends CountDownTimer {
    public CountDownTimerTest(long startTime, long interval) {
        super(startTime, interval);
    }

    @Override
    public void onFinish() {
        text.setText("Time's up!");
        timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
    }

    @Override
    public void onTick(long millisUntilFinished) {
        text.setText("Time remain:" + millisUntilFinished);
        timeElapsed = startTime - millisUntilFinished;
        timeElapsedView.setText("Time Elapsed: " + String.valueOf(timeElapsed));
    }
}

Then on my btn1, I put this code (start the CountDownTimer):

countDownTimer.start();

And on my btn2, I put this code (stop/cancel the CountDownTimer):

countDownTimer.cancel();

Now, I hope that you can understand how CountDownTimer works, if your question isn't about CountDownTimer, let me know, and I'll update my answer as soon as possible with your wishes.

EDIT - Only with one Button

To do it with the same Button, you can do this:

Create a Boolean variable as:

Boolean ButtonClicked = false;

And then, modify the code as follows:

btn1.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        if (!ButtonClicked)) {
            ButtonClicked = true;
            countDownTimer.start(); 
        } else {
            ButtonClicked = false;
            countDownTimer.cancel();
        }                       
    });
}

EDIT 2 Get what button is clicked

You can create an int called NumberButtonClicked like this :

int NumberButtonClicked = 0;

Then on every Button you have you'll have to do this (Example) :

btn1.setOnClickListener(new OnClickListener() {
    @Override
        public void onClick(View arg0) {
            NumberButtonClicked = 1;
    });
}

Then you know that if you have clicked btn1 your variable will be 1.

Skizo-ozᴉʞS ツ
  • 19,464
  • 18
  • 81
  • 148
  • Ok thank you, but how does it works with one button, so you press the button and the timer runs till hes over? – Phil Jul 26 '15 at 17:07
  • Be careful when using Timer, because it's not stop when you leave your activity. It may cause NPE if you update views in that case. – Tien Jul 26 '15 at 17:46
  • 1
    Good comprehensive answer. Downvoting someone's very first question on SO without providing guidance or answer is just mean. – Noobification Jul 26 '15 at 18:56
  • Thank you for youre time and this great answer. – Phil Jul 26 '15 at 19:14
  • If it helped you **must** mark it as a correct answer :) – Skizo-ozᴉʞS ツ Jul 26 '15 at 19:15
  • I only have a last question, is there a way to get a boolean value from onclick? or do i need a global var? – Phil Jul 26 '15 at 19:38
  • What do you mean @Phil? I don't understand what are you asking to me – Skizo-ozᴉʞS ツ Jul 26 '15 at 19:41
  • Ok the background is i need 4 buttons and when the buttons are clicked, time will be added to the counter, but i want to know which button is clicked, so i hoped that there is some return value from the onClick() Method from a Button? – Phil Jul 26 '15 at 20:00
  • @Phil What do you want to return? – Skizo-ozᴉʞS ツ Jul 26 '15 at 20:09
  • Something what fits like if(button.onClick() == true) – Phil Jul 26 '15 at 20:21
  • @Phil See the edit, if you don't understand you can join on this [chat](http://chat.stackoverflow.com/rooms/54844/persian-chat) and I'll help you – Skizo-ozᴉʞS ツ Jul 26 '15 at 20:35
  • Ok Thank you, thats a good idea, its late i sleep now, i got problems with private Button right = (Button)findViewById(R.id.right); right.setOnClickListener(new OnClickListener() {/* Some Code */ }); it says ->invalid method declaration; return type requiered. I'm to tired to take a closer look, so thank you for all – Phil Jul 26 '15 at 20:51
  • Nicely explained. +1 ;) – Tushar Gogna Jul 27 '15 at 04:48
  • Got another problem, need to add time to the countdowntimer but i read that is not possible, i need to cancel one and start a new. But why? the countdowntimer class must have a parameter which show the remaining seconds or? – Phil Jul 27 '15 at 17:51
  • You can see this [question](http://stackoverflow.com/questions/17383584/how-to-add-time-to-countdown-timer) or search on StackOverflow... I think your quesiton is answered correctly that's why you have to mark it as a correct and if you have more doubts you have to create another question and if you want you give me the question url :) – Skizo-ozᴉʞS ツ Jul 27 '15 at 18:09