1

My application has a timer, which I want to keep running in two situations: Change screen orientation and when the back button is pressed and exits the application.

       chronometer= (Chronometer) rootView.findViewById(R.id.chronometer);
       chronometer.setBase(SystemClock.elapsedRealtime());
       chronometer.start();

I would like to know what methods have to put the code, and what code to handle everything related to the chronometer.

1 Answers1

0

At activity start:

void onCreate() {
   chronometer = (Chronometer) rootView.findViewById(R.id.chronometer);
   resetAndRun();
]

where:

void resetAndRun() {
   // reset base time to current
   chronometer.setBase(SystemClock.elapsedRealtime());
   // and start ticking
   chronometer.start();

}

This will start your app with a ticking timer.

Now, to listen for back press (which, BTW, does not equal app close in Android):

public void onBackPressed() {
  resetAndRun();
  super.onBackPressed();
}

Here is a tricky point: after back press the screen will no longer be visible to the user but still the clock will tick and, next time when activity becomes visible, the updated timer value will be shown.

Listening and reacting to screen orientation requires manifest declaration:

<activity android:name=".MyActivity"
          android:configChanges="orientation|screenSize"  // <--------------
          android:label="@string/app_name">

And an activity callback:

public void onConfigurationChanged(Configuration newConfig) {
   super.onConfigurationChanged(newConfig);
   resetAndRun();
}

Hope it helps.

Gilad

Gilad Haimov
  • 5,767
  • 2
  • 26
  • 30
  • I think I did not explain well. My application has a timer, that pressing a button starts. To changes, such as changing the orientation of the screen or press the back button and exit the application, the timer is set to 0 (and stops). I wanted to know how to make the clock keep running and the time on the same is correct. (If the orientation is changed, will the time was right before changing direction. For exit the application, will be the time when most marking out the time it was out of the application) However, thanks for the previous answer. – user3764379 Jun 29 '14 at 16:08