MilindaD
MilindaD

Reputation: 7653

Calculate Duration

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

Upvotes: 10

Views: 25842

Answers (4)

FBH
FBH

Reputation: 793

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

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

Upvotes: 0

Łukasz Wachowicz
Łukasz Wachowicz

Reputation: 535

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

Upvotes: 13

Vivek
Vivek

Reputation: 4260

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;

Upvotes: 0

WhiteFang34
WhiteFang34

Reputation: 72039

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;

Upvotes: 23

Related Questions