0

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?

4

3 回答 3

2

static long nanoTime()

返回本地系统上可用的最精确计时器的当前时间戳。

您没有使用“计时器”(即任何类型的有状态对象)来表示经过的时间,您只是在坚持很长时间。正如您所指出的,您将在将来的某个时间再次调用 System.nanoTime() 并减去以找到经过的时间。

如果您想排除在此活动之外花费的时间,例如您问题中的示例,您将需要使用onPause()onResume()帮助您管理计算。或者,如果您切换到某种计时器对象,请使用这些方法来暂停和恢复计时器。

您可以在您认为最有意义的任何地方“启动”您的“计时器”。如果是在用户启动某些操作(如按下按钮)时,请在 OnClickListener 中进行操作。如果只是为了测量某个方法/代码路径运行了多长时间,请在开始时进行。

于 2013-07-08T16:27:44.207 回答
1

根据文档

System.nanoTime()返回最精确的可用系统计时器的当前值,以纳秒为单位。

所以它不是计时器。它只是以纳秒为单位返回系统时间。它与活动无关。

如果要测量活动的生命周期,请在 onCreate 和 onDestroy 中获取时间。如果您想知道活动在前台运行了多少时间,请在 onResume 和 onPause 中获取时间。

于 2013-07-08T16:27:18.813 回答
0

您将需要覆盖Activity 类中的onPause()onResume()方法,以便您可以暂停计时器。并在 onResume 中恢复。

你应该把 System.nanoTime() 放在 onResume()

于 2013-07-08T16:23:38.837 回答