views:

138

answers:

2
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;
    }
}
+1  A: 

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.

Nikola Smiljanić
So, my timer is completely different than my service? Even if I stop my service...my timer runs? Why?
TIMEX
I don't know why, but if you start 10 threads from your service and you stop it, they will continue to run.
Nikola Smiljanić
Why? Because as far as Android is concerned your Timer is not tied to your service.
Stephen C
What do you mean 10 threads? I only start one :)
TIMEX
Thanks Stephen.
TIMEX
I just wanted to illustrate what Stephen said, they are not connected in any way. To you it might seem like they are because you start your timer from the service, but that's not the case.
Nikola Smiljanić
+4  A: 

To make the Timer go away when your service is stopped, you need to call cancel() on the Timer in the appropriate callback method for the service; onDestroy by the looks of it.

Even if I stop my service...my timer runs? Why?

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.)

Stephen C