当 Android 应用程序位于前台时运行线程
我有一个 Android 应用程序。我有一个主要活动,有一个按钮。单击该按钮时,另一个活动将进入前台。问题是,我想运行一个后台线程来轮询服务器的更新。但是,我希望它仅在应用程序位于前台(主要活动或第二个活动)时运行,并在用户单击“主页”按钮或单击“后退”按钮时停止轮询,直到它从主要活动返回。
但我如何知道应用程序是否仍在前台?我可以捕获主要活动的 onPause,但当我启动第二个活动时也会调用它。
那么我如何知道应用程序何时处于后台?
谢谢
I have an Android app. I have a main activity, that has a button. When the button is clicked, another activity comes to the foreground. The thing is, I want to run a background thread that polls updates from the server. However, I want it to run only when the app is in foreground (either the main activity or the second one), and to stop polling when the user clicks the Home button or clicks the Back button till it's going back from the main activity.
But how do I know if the app is still in the foreground? I can catch the onPause of the main activity, but it's called also when I'm launching the second activity.
So how do I know when the app is in background?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该为您在后台所做的工作创建一个服务。
要在单击“主页”或“后退”按钮时停止它,只需为它们创建一个侦听器并在按下任一按钮时停止服务即可。
You should make a Service for the work you are doing in the background.
For stopping it when you click the Home or Back button, just make a listener for them and stop the Service when either one is pressed.
对我来说,每个活动进行轮询似乎是最简单的。在两个活动之间进行轮询是否非常重要?否则你会很难知道谁在前面或不在前面。
Seems easiest to me that each activity polls. Is it super important that it can poll when it is between the two activities? Otherwise you will have problems about knowing who is in front or not.
您可以拥有一个带有引用计数的单例。
您的主要活动应该在其 onResume 上添加第一个引用,从现在开始,在调用每个新活动(例如 startActivity)时,您应该添加一个引用。
每个活动都应该减少其 onPause 的引用计数。
另一种选择是使用服务:服务
You can have a singleton with reference counting.
You main activity should add the first reference on it's onResume and from now, upon calling for every new activity (startActivity for example) you should add a reference.
Each activity should decrease the reference counting on its onPause.
Another option is to use services: Services