I have an activity in which I want to track the time elapsed between two actions(for example startAction and endAction). I’ve used the following code to implement a timer that increments every 500 ms after the user presses the button for startAction:
TextView dayTimer = (TextView)findViewById(R.id.tvDayTimer);
long startTime;
class DayTimer extends TimerTask {
@Override
public void run() {
BBCAndroid.this.runOnUiThread(new Runnable() {
public void run() {
long millis = SystemClock.elapsedRealtime() - startTime;
int seconds = (int) (millis / 1000);
int minutes = seconds / 60;
seconds = seconds % 60;
dayTimer.setText(String.format("%d:%02d", minutes, seconds));
}
});
}
};
startDayButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startTime = SystemClock.elapsedRealtime();
timer.schedule(new DayTimer(), 0,500);
LoginResult.DayState = 1;
startDayButton.setEnabled(false);
endDayButton.setEnabled(true);
}
});
Now my problem is that, if I exit the application the timer stops. How can I make it run even when the user is out of the app?
In summary, I need a timer that counts even if the app is closed.
You can start a Service and it will be up and running even if your application is closed.
Here is a good tutorial.