2012-02-23 87 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