Sergio76
Sergio76

Reputation: 3986

I can't stop a simple service

I know that this question has already been asked, but the solutions I find do not solve the problem, at least for me.

I have a simple service that I call at a certain time from an activity. This service executes an action every three seconds. The service works well, but after reading a lot about the subject and trying all the solutions I find, I can't destroy the service and stop it. the onStartCommand method always runs again and I start over.

Can someone tell me the changes I have to make in my code to stop the service completely and destroy it?

I insist, stopSelf(), stopService(), etc, etc ... At no time has the service stopped

Thank you very much and I leave my code:

public class myService extends Service {

  //...

    @Override
    public void onCreate() {

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        if (mTimer != null) {

        } else {
            mTimer = new Timer();
        }

        mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);

        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public void onDestroy() {

        Log.e(TAG,"Service onDestroy");

    }

    class TimeDisplayTimerTask extends TimerTask {

        @Override
        public void run() {
            // run on another thread
            mHandler.post(new Runnable() {

                @Override
                public void run() {

                    vuelta  = vuelta +1;

                    if (vuelta==2){

                        stopSelf();

                    } else {
                        // NA
                    }

                }

            });
        }
    }
}

Upvotes: 1

Views: 66

Answers (1)

greeble31
greeble31

Reputation: 5042

If "Service onDestroy" prints to logcat, then your Service has indeed stopped. That does not mean that your Timer has stopped.

The Android framework has no way of knowing what threads are associated with your Service, so it does not take the liberty of killing any particular thread when it decides to destroy your Service. This is true even if the Service object itself is GC'd. (As implemented, though, your myService object will not be GC'd, because there are several references to it via the Timer thread and the TimeDisplayTimerTask within that Timer.)

You may find that the Timer stops running eventually, some minutes after you had commanded the Service to stop; this is likely because Android has terminated your app entirely, in order to free up resources for higher priority apps, and/or the "foreground" app.

To improve the situation, you should purge() your Timer in onDestroy().

Upvotes: 1

Related Questions