[英]onDestroy being called but service not ending
我正在閱讀“開始Android 4開發”一書,我正在使用按鈕中的以下功能來控制服務:
public void startService(View view) {
startService(new Intent(getBaseContext(), QOLService.class));
}
public void stopService(View view) {
stopService(new Intent(getBaseContext(), QOLService.class));
}
QOLService.java包括
public class QOLService extends Service {
int counter = 0;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Keep running service until stopped, so return sticky
Timer timer=new Timer();
TimerTask tt =new TimerTask() {
@Override
public void run() {
Log.d("QOLService", String.valueOf(++counter));
}
};
timer.scheduleAtFixedRate(tt, 0, 1000);
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
}
按照預期,在按下開始按鈕時,我得到'service started'toast,在logcat中,我得到一條消息每秒遞增一次。 即使應用程序關閉,這仍將按預期繼續進行。
當我點擊停止服務按鈕時,我也得到了預期的“服務銷毀”消息,但計時器依然存在! 如果我關閉應用程序,它仍然繼續。 如果我再次單擊stopservice按鈕,它不會給出服務銷毀消息,就好像它第一次被成功銷毀一樣。
我不恰當地打電話給我的計時器嗎? 如果是這樣的話,我似乎正如本書所建議的那樣做!
我不恰當地打電話給我的計時器嗎?
你永遠不會停止計時器。 因此,它將一直運行,直到該過程終止。 你應該在onDestroy()
停止計時器。
我同意CommonsWare,你沒有在代碼中停止你的計時器。 我建議你走這條路,
public class QOLService extends Service {
int counter = 0;
Timer timer;
TimerTask tt;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Keep running service until stopped, so return sticky
timer=new Timer();
tt =new TimerTask() {
@Override
public void run() {
Log.d("QOLService", String.valueOf(++counter));
}
};
timer.scheduleAtFixedRate(tt, 0, 1000);
Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed", Toast.LENGTH_LONG).show();
tt.cancel();
timer.cancel();
}
}
cancel()方法將停止你的Timer以及。
這可能是因為系統正在嘗試重新啟動您的服務,因為您從onStartCommand
返回START_STICKY
。 請嘗試返回START_NOT_STICKY
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.