Why can't I stop a service in Android?

2019-09-06 12:34发布

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;
    }
}

2条回答
女痞
2楼-- · 2019-09-06 12:57

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

查看更多
乱世女痞
3楼-- · 2019-09-06 13:17

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.

查看更多
登录 后发表回答