androidtimerelapsed

What does System.nanoTime() return in Android?


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?


Solution

  • 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()