Stopping and starting a Service based on applicati

2019-02-10 01:05发布

I have a Service which tracks the location of the user. Currently, the Service boots when the application starts and stops when the application terminates. Unfortunately, if users keep the application in the background, the Service never stops and drains battery.

I would like the Service to stop when my application is not in the foreground. I was hoping the Application class would let me Override onPause and onResume handlers, but it does not have them. Is there another way I can accomplish this?

8条回答
不美不萌又怎样
2楼-- · 2019-02-10 01:35

Try using the Bound Services technique to accomplish this.

Bound Services | Android Developers

You can use bound services in a way such that the service will stop when no activities are bound to it. This way, when the app is not in the foreground, the service will not be running. When the user brings the app back to the foreground, the Activity will bind to the service and the service will resume.

查看更多
Animai°情兽
3楼-- · 2019-02-10 01:36

You should override the onPause and onResume methods on your Activity. If you have multiple activities you may want to have a common base class for them and put the start/stop logic into the base class.

查看更多
登录 后发表回答