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
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.
If you want to find out how long activity is open.
You can write respective code in
onCreate() method and onDestory()
- 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);