屏幕关闭时服务被终止
我有一项获取 GPS 坐标的服务。问题是当屏幕关闭时它会被杀死。如何让服务即使在屏幕打开的情况下也能工作。
I have a service that gets GPS coordinates. The problem is it gets killed when the screen turns off. How can make the service to work even if the screen is turned on.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您使用 Context.bindService() 启动服务,则其生命周期(包括何时停止)将绑定到特定的调用上下文(可能是您的 Activity)。当您的 Activity 关闭时,您的服务也会关闭。这就是您关闭屏幕时所经历的情况。
如果您希望其生命周期独立于 Activity,请使用 Context.startService() - 这将确保即使您关闭屏幕它也能保持活动状态。当你想停止服务时,可以调用Context.stopService()。
http://developer.android.com /reference/android/content/Context.html#startService(android.content.Intent)
If you start your service with
Context.bindService()
, its lifecycle (including when it will be stopped) is bound to the particular calling context (likely to be your Activity). When your Activity shuts down, so will your service. This is what you are experiencing when you turn off your screen.Use
Context.startService()
if you wish for its lifecycle to be independent of the Activity - this will make sure it will stay alive even if you turn off the screen. You can call Context.stopService() when you want to stop the service.http://developer.android.com/reference/android/content/Context.html#startService(android.content.Intent)