Calculate Duration

末鹿安然 提交于 2020-01-12 17:29:06

问题


I have a small android problem, I have a requirement to have a timer to calculate the duration from the time a specific activity was open till a certain button in that activity is clicked, simply how long the activity was open. While googling around I found TimerTask but this seems to run a thread for a certain interval only though and doesent seem ideal for the job from my little Android experience

Any idea on how to calculate the duration? Preferably in a very simple manner

Any help is very welcome

Regards, MilindaD


回答1:


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;



回答2:


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




回答3:


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;



回答4:


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

 StopWatch stopWatch = new StopWatch();
 stopWatch.start();
       ...
 stopWatch.stop();
 stopWatch.getTime(TimeUnit.SECONDS);


来源:https://stackoverflow.com/questions/5562550/calculate-duration

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