我已閱讀了很多帖子,但無法找到我的具體問題的答案。安卓定時器在服務 - 如何停止和啓動
下面的服務運作良好。我可以開始它。開始。我可以阻止它。它停下來。我可以重新啓動一個新的時間間隔。這也適用。當我停止時,它不會停止。在onDestroy中,這是timer = null的情況。如果我將timer.cancel插入到timer = null情況下的onDestroy中,那麼我會在執行空指針時發生崩潰。然而,它仍然在運行,如日誌輸出所示!
這裏是日誌輸出,如果有幫助的(最後的 「noOutRows」 後,它只是不斷運行)
E/ timer: startservice
E/ timer: timeInterval 1000
E/ timer: isNotNull
E/ timer: no noOutRows 1503945704743
E/ timer: no noOutRows 1503945705712
E/ timer: no noOutRows 1503945706714
E/ timer: no noOutRows 1503945707713
E/ timer: no noOutRows 1503945708712
E/ timer: stopservice
E/ timer: stop - isNotNull
E/ timer: startservice
E/ timer: timeInterval 5000
E/ timer: isNull
E/ timer: no noOutRows 1503945744406
E/ timer: no noOutRows 1503945749407
E/ timer: no noOutRows 1503945754407
E/ timer: stopservice
E/ timer: stop - isNull
E/ timer: no noOutRows 1503945759407
E/ timer: no noOutRows 1503945764407
E/ timer: no noOutRows 1503945769773
這裏是我的代碼
public class LocalService extends Service
{
public Integer timeInterval = 1000;
private static Timer timer = new Timer();
public IBinder onBind(Intent arg0)
{
return null;
}
@Override
public void onCreate()
{
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(" timer"," startservice");
int newTimeInterval = intent.getIntExtra("time_interval", -99);
timeInterval = newTimeInterval;
Log.e(" timer ", " timeInterval " + timeInterval);
if (timer == null){
Log.e(" timer"," isNull");
Timer timer = new Timer();
timer.scheduleAtFixedRate(new mainTask(), 0, timeInterval);
} else {
Log.e(" timer"," isNotNull");
timer.scheduleAtFixedRate(new mainTask(), 0, timeInterval);
}
return START_STICKY;
}
private class mainTask extends TimerTask
{
public void run()
{
logHandler.sendEmptyMessage(0);
}
}
public void onDestroy()
{
Log.e(" timer"," stopservice");
if (timer != null) {
Log.e(" timer"," stop - isNotNull");
timer.cancel();
timer = null;
} else {
Log.e(" timer"," stop - isNull");
}
super.onDestroy();
}
private final Handler logHandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
int maxRows = MainActivity.Cache.alls.size()-1;
if (maxRows > 0) {
Log.e(" timer ", " outRows " + maxRows + " " + MainActivity.Cache.alls.get(maxRows).toString());
} else {
Log.e(" timer ", " no noOutRows " + MainActivity.utcNow().getTime());
}
}
};
}
這難道不正常嗎? https://stackoverflow.com/q/9093271/1531971 – jdv
謝謝。好問題。我對START_STICKY不是很熟悉。不過,我會嘗試下面的Runnable方法。 –