Question

I have a bunch of activities tied together, one into the next and so on. Now during one activity I want to measure elapsed time. As I understand, I would use System.nanoTime() to find the start time, the user does some things, then use it once more to find the end time, subtract the two and voila my elapsed time spent on the activity. But suppose something happens while my activity is running: I already have created the start time, but now the user gets a phone call or something, my activity is put into the background. The phone call ends and the user returns to the activity. Was the timer running the whole time, even while the app was in the background? Is the timer 'reset' since I left the app then came back to it?

Also, when I do initiate System.nanoTime() is it returning the time since the start of that particular activity or the main activity?

EDIT: Suppose I set the first tickmark at a certain point, then the app goes into the background, then it returns to the foreground and I set the second tickmark. Ideally I want the time elapsed along with the time spent in the background; does System.nanoTime() achieve this?

Was it helpful?

Solution 3

You will need to override onPause() and onResume() methods in the Activity class so you can pause your timer in pause. and resume in onResume.

You should put System.nanoTime() on onResume()

OTHER TIPS

static long nanoTime():

Returns the current timestamp of the most precise timer available on the local system.

You aren't using a "Timer" (that is, a stateful object of any kind) to represent the elapsed time, you are just hanging on to a long. As you pointed out, you will call System.nanoTime() again at some future point and subtract to find the elapsed time.

If you want to exclude time spent outside of this activity, like the example in your question, you will need to use onPause() and onResume() to help you manage the calculations. Or, if you switch to some kind of timer object, use these methods to pause and resume the timer.

You can "start" your "timer" wherever you think makes the most sense. If it's when the user initiates some action (like a button press), od it in an OnClickListener. If it's just to measure how long some method/code path runs, do it at the beginning of that.

according to the doc

System.nanoTime() returns the current value of the most precise available system timer, in nanoseconds.

So it is not an timer. It just returns the system time in nano seconds. It has not relation with activity.

If you want to measure the lifetime of activity then get the time in onCreate and onDestroy. And if you want the time to know how much time the activity was in foreground then get the time in onResume and onPause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top