2012-02-23 89 views
4

我的应用程序中有一个计时器,它关闭了应用程序,并使用一个处理程序实现了我发布延迟的可运行“退出”的应用程序。当用户点击计时器图标时,它也应该显示剩下多少时间。我怎么能得到这些数据? 我应该实现一个可以计算秒数并使用该数据的对象吗?Android:获得时间,直到通过处理程序执行Runnable

回答

4

我更喜欢使用ScheduledExecutorServiceScheduledFuture,这些API比处理程序和定时器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); 
... ... 

希望有所帮助。

+0

谢谢,这会削减工作。 – 2012-02-23 22:06:27

+0

请注意,[''TimeUnit.MINUTES'不保证在Android上存在](http://stackoverflow.com/questions/3472423/android-java-util-concurrent-timeunit-convert-milliseconds-to-minutes) – 2014-01-31 16:32:58