开发者

When should a Service be stopped

My android application starts a service in the onCreate() callback of a class that extends Application. The service performs some background tasks that are relevant to the user only while the application is running. For that reason I would like to close the service when the application's last activity is closed. I've tried to perform closing the service in开发者_开发百科 the callback onTerminate() , but it never gets called . So what would be the best place where a service should be closed ?

Thanks !


An Android service, once started, will continue running until the Context.stopService() or stopSelf() is called.

There are various hooks you can use to stop the service using Context.stopService (the service itself, or an onDestroy()/onPause callback in one of the activities, or a button click).

It's true that Android does some resource management itself, but it can take a long time before Android decides to terminate your services. And a service that's running but not doing anything just consumes resources on the phone that other apps might need.

In your case, the onPause method of your last activity would be a good that will get called, and as such is the correct place to stop the service.


The onPause() callback will be made when your activity is paused for any reason, and you know that when this happens your app will not be visible again until onResume() is called. If your service has a reason to run in the use case that your activity might be started again soon, you should add an entry to your service that onPause() calls, to set a delayed service termination. In onResume() you can cancel that delayed termination through another entry.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜