Reputation: 6150
I have a timer in my app which shut's down the app implemented with a handler to which I post a delayed runnable "quit". When user clicks the timer icon it should also show how much time is left. How could I get this data? Should I implement an object which would count the seconds and use that data?
Upvotes: 4
Views: 1302
Reputation: 41126
I prefer to use ScheduledExecutorService with ScheduledFuture, these API are more efficient and powerful than Handler and Timer IMO:
ScheduledExecutorService scheduledTaskExecutor = Executors.newScheduledThreadPool(1);
Runnable quitTask = new Runnable();
// schedule quit task in 2 minutes:
ScheduledFuture scheduleFuture = scheduledTaskExecutor.schedule(quitTask, 2, TimeUnit.MINUTES);
... ...
// At some point in the future, if you want to get how much time left:
long timeLeft = scheduleFuture.getDelay(TimeUnit.MINUTES);
... ...
Hope that helps.
Upvotes: 4