1

I require that from one activity (e.g Apple) a timer is automatically started to run for 20 secs and once the timer ends, its suppose to end to another activity (e.g. Orange).

But there is a button in Apple that allows me to click to another Apple activity (essentially a repeat), and the timer resets again in the new Apple.

The code for the timer as follows

       new CountDownTimer(20000, 1000) {
       public void onTick(long millisUntilFinished) {

    public void onFinish() {
        Intent i = new Intent(Apple.this, Orange.class);
        Log.i(LG, "From Apple to Orange");

        startActivity(i);   
    }
 }.start();

If the Apple is activated once and exit to Orange, there's no problem.

But if one Apple(1) activity is activated followed by another Apple(2) activity, it seems that the timer for the Apple(1) does not stop. For example, if the I exit Apple(1) to Apple(2) when Apple(1) at 10 secs, for Apple(2), it only counts to 10 secs (not the full 20 secs) before exiting to Orange.

Where did I go wrong?

user3492802
  • 179
  • 9

1 Answers1

2

This is happening because you are not saving the instance state of Apple. You have some options :

1) You could move the timer off the UI thread:

Resuming CountdownTimer after rotation

2) It may be simpler to just save the instance of millisUntilFinished when Apple calls Apple and then resume the timer from that value in the second instance. This should help (you use your activity's onPause and onResume methods):

Countdown timer with pause and resume

Community
  • 1
  • 1
IanB
  • 3,489
  • 1
  • 20
  • 24
  • I'm afraid I'm very new to android and Java. I read through your link and I'm not sure how it applies to my case. How do I save the instance of the millisUntilFinished? Btw, it does not have to be super accurate. Its essentially a reset of the apple to refresh the 'time remaining' each time the user click from apple to apple. Note also, I expect the user to typically go through an average of 20+ Apples before going to Orange – user3492802 Jun 26 '14 at 14:54
  • Fine, the second suggestion is probably an easier approach for you to use. It looks to me as though you could copy the code and make it work with relatively little modification ... – IanB Jun 26 '14 at 15:32