Android:应用程序全局 onPause() 和 onResume()?
是否有类似应用程序全局 onPause()
和 onResume()
的东西?
我的主要活动监听 GPS 修复,我希望在切换到另一个屏幕/活动时继续工作。因此,我无法在活动的 onPause()
中取消注册我的 LocationListener
。但是,我仍然想在切换到另一个应用程序时注销我的 GPS 侦听器(以便节省电池),并在返回我的应用程序时将其重新打开,无论用户当前处于哪个屏幕/活动中。
有什么想法吗?
Is there something like an application global onPause()
and onResume()
?
My main activity listens for GPS fixes, which I want to continue working when switching to another screen/activity. Therefor I cannot unregister my LocationListener
in the activity's onPause()
. However I still want to unregister my GPS listener when switching to another application (so save battery) and turning it back on when returning to my application, regardless what screen/activity the user is currently in.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,抱歉。
这是一种可能的方法:
步骤 #1:将
LocationListener
逻辑移至Service
中,活动通过本地绑定模式或其他方式连接到该服务。还至少有一个服务调用startService()
,因此unbindService()
不会导致Service
消失(假设您'使用本地绑定模式)。步骤#2:让活动在
onPause()
和onResume()
期间调用服务。步骤#3:让服务维护未完成活动的引用计数。
步骤#4:当引用计数达到零时,安排服务通过 Timer 和 TimerTask 唤醒。另外,如果引用计数增加,请取消任何此类未完成的 TimerTask。
步骤#5:让
TimerTask
在执行时关闭GPS。实际情况是,只有在一定程度的不活动后,您才会释放 GPS。这种不活动可能是出于任何原因。
No, sorry.
Here's one possible approach:
Step #1: Move the
LocationListener
logic into aService
, which the activities connect to via the local binding pattern or something. Also have at least one service callstartService()
, so anunbindService()
won't cause theService
to go away (assuming you're using the local binding pattern).Step #2: Have the activities call into the service during
onPause()
andonResume()
.Step #3: Have the service maintain a reference count of outstanding activities.
Step #4: When the reference count reaches zero, have the service arrange to get woken up via a Timer and
TimerTask
. Also, cancel any such outstandingTimerTask
if the reference count gets incremented.Step #5: Have the
TimerTask
shut down GPS if it ever gets executed.The net is that you will only release GPS after such-and-so amount of inactivity. That inactivity could be for any reason.
使用 ActivityLifecycleCallbacks。在您的应用程序中注册它:
Use ActivityLifecycleCallbacks. Register it in your Application: