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