Calculate Duration

廉价感情. 提交于 2019-12-04 03:31:39

Just use System.currentTimeMillis() to capture the time when the activity starts and stops. E.g.:

long startTime = System.currentTimeMillis();
// wait for activity here
long endTime = System.currentTimeMillis();
long seconds = (endTime - startTime) / 1000;

As of Java 8 there is more convenient way of doing this.

Instant start = Instant.now();
...
Duration.between(start, Instant.now())

Benefit of this approach is more flexible API provided by the Duration class.

https://docs.oracle.com/javase/8/docs/api/java/time/Duration.html

If you want to find out how long activity is open.

You can write respective code in

  • onCreate() method and onDestory() method. or

  • onResume() method onPause() method.

depending on your need.

and make use of following code

long t1 =  new Date().getTime();
long  t2 = new Date().getTime();
long t3 =  t2 - t1;

group: 'org.apache.commons',name: 'commons-lang3'

 StopWatch stopWatch = new StopWatch();
 stopWatch.start();
       ...
 stopWatch.stop();
 stopWatch.getTime(TimeUnit.SECONDS);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!