Intent helloservice = new Intent(this, HelloService.class);
startService(helloservice);
...
stopService(helloservice);
Why won't this work? It just keeps running. Am I missing some Binds or something?
By the way, this is my service:
public class HelloService extends Service {
private Timer timer = new Timer();
private long INTERVAL = 1000;
public void onCreate() {
super.onCreate();
startservice();
}
private void startservice() {
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
Log.d("service", "This proves that my service works.");
}
}, 0, INTERVAL);
; }
@Override
public IBinder onBind(Intent arg0) {
return null;
}
}
To make the
Timer
go away when your service is stopped, you need to callcancel()
on theTimer
in the appropriate callback method for the service;onDestroy
by the looks of it.Because, as far as the Android operating system is concerned, the Timer instance is not logically tied to any particular service. It is the Service implementation's responsibility to deal with releasing any resources that the garbage collector won't deal with. (Open file handles and database connections are other examples I imagine.)
It does stop your service. Override onDestroy in your service and you'll see that it's called. But service != timer, you have to stop your timer manually.