我想在特定時間開始任務。對於我使用runnable
和postDelayed
方法如下:使用postDelayed在特定時間運行任務
private Runnable mLaunchTask = new Runnable() {
public void run() {
try {
MY TASK
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
};
在我的代碼我使用mLunchTask
如下:
mHandler = new Handler();
mHandler.postDelayed(mLaunchTask, myDelay*1000);
和myDelay
計算如下:
s = DateFormat.format("hh:mm:ss aaa", d.getTime());
cTime = s.toString(); // current Time
ch = Integer.parseInt(cTime.substring(0,2)); // current hour
cm = Integer.parseInt(cTime.substring(3,5)); // current minute
cs = Integer.parseInt(cTime.substring(6,8)); // current second
if (cTime.substring(9,11).equalsIgnoreCase("pm") && (ch<12)) ch = ch+12;
myDelay=(desiredHour-ch)*3600+(desiredMinute-cm)*60 - cs;
if (myDelay<0) myDelay = 0;
和desiredHour
和desiredMinute
由用戶設置。預期MY TASK
開始於desiredHour
和desiredMinute
和0秒。 但是「我的任務開始用幾秒鐘的延遲,這看起來是隨機的。
基於上面的代碼中,沒有任何理由,它並沒有確切的所需時間開始?
感謝
啊,mLunchTask:我的最愛:) –