好吧,由于我缺乏使用Android的经验,因此我可能会略有错误,但是一切正常。有时我得到意想不到的结果。这是使用Timer的严格删节代码:
private Timer timer;
private TimerTask timerTask;
public void startTimer() {
timer = new Timer();
initializeTimerTask();
timer.schedule(timerTask, 10000, 10000);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
runSendJob(jsonData, SentReceiver);
// wait up to 10 seconds for response from broadcast receiver
long startTime = System.currentTimeMillis();
while(bResult.equals(false) && (System.currentTimeMillis()-startTime)<10000){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (bResult.equals(true)){
UpdateLog();
}
}
};
}
}
“空闲”时,initializeTimerTask()每10秒钟运行正常,无事可做,但如果runSendJob进行一些工作,则可能需要10到20秒才能完成,等待BroadcastReceiver响应,设置返回标志并继续,然后计时器立即再次运行。
我希望它等待10秒,所以我进行了如下修改。现在看来运行良好,等待了10秒钟才再次骑自行车(感谢提示@notTdar);
public class MyService extends Service {
BroadcastReceiver SentReceiver;
public Boolean bResult;
@Override
public void onCreate() {
super.onCreate();
mHandler = new Handler();
commandStart()
}
private void commandStart() {
if (mExecutor == null) {
mExecutor = Executors.newSingleThreadScheduledExecutor();
Runnable runnable =
new Runnable() {
@Override
public void run() {
startMyTask();
}
};
mExecutor.scheduleWithFixedDelay(runnable, DELAY_0, DELAY_10, DELAY_SECONDS);
d(TAG, "commandStart: starting executor");
} else {
d(TAG, "commandStart: do nothing");
}
DeliveredReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context arg0, Intent arg1) {
switch(getResultCode()) {
case Activity.RESULT_OK:
bResult = true;
break;
case Activity.RESULT_CANCELED:
bResult = false;
break;
}
}
};
registerReceiver(SentReceiver, new IntentFilter("MSG_SENT"));
}
public void startMyTask() {
runSendJob(jsonData, SentReceiver);
// wait up to 10 seconds for response from broadcast receiver
long startTime = System.currentTimeMillis();
while(bResult.equals(false) && (System.currentTimeMillis()-startTime)<10000){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (bResult.equals(true)){
UpdateLog();
}
// spin off other jobs here if I want to...
mHandler.post(
new Runnable() {
@Override
public void run() {
updateSomethingElse();
}
});
}
}