根据应用程序状态停止和启动服务 [英] Stopping and starting a Service based on application state

查看:55
本文介绍了根据应用程序状态停止和启动服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个跟踪用户位置的服务.目前,服务在应用程序启动时启动,在应用程序终止时停止.不幸的是,如果用户将应用程序保持在后台,则服务永远不会停止并耗尽电池电量.

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.

当我的应用程序不在前台时,我希望服务停止.我希望 Application 类能让我覆盖 onPause 和 onResume 处理程序,但它没有它们.我还有其他方法可以做到这一点吗?

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?

推荐答案

我还没有测试过这个,但看起来如果你使用 Context#bindService() (而不是 Context#startService()),服务应该在没有更多活动绑定到它时停止.(请参阅服务生命周期).

I haven't tested this yet, but it looks like if you use Context#bindService() (instead of Context#startService()), the service should stop when no more activities are bound to it. (see Service lifecycle).

然后在每个 Activity 中使用 onPause()/onResume() 绑定/取消绑定服务.

Then use onPause()/onResume() in each activity to bind/unbind from the service.

或者,您可以在您的服务上添加一对方法,告诉它开始/停止侦听位置更新,并从每个活动的 onResume()/onPause().服务仍会运行,但位置更新不会耗尽电池电量.

Alternatively, you could add a pair of methods on your service which tell it to start/stop listening for location updates and call it from each activity's onResume()/onPause(). The service would still be running, but the location updates wouldn't be draining the battery.

这篇关于根据应用程序状态停止和启动服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆