[英]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.