Android的:如何知道什么时候一个应用程序进入或"背景"模式?什么时候、应用程序、背景、模式

2023-09-05 06:09:16 作者:亡心咒

我想实现与Android如下:

I am trying to achieve the following with Android :

当应用程序在后台,一个线程轮询服务器飘飞检索数据,并通知用户,如果新的数据是可用的。我使用该服务,精细。

when the app is in background, a thread polls a server every now and then to retrieve data and notifies the user if new data is available. I am using a Service for that, fine.

在应用程序处于激活使用,即它的活动之一是可见的,轮询应该停止,因为它可能会与其他用户的操作造成干扰。

when the app is in "active" use, i.e. one of its activities is visible, the polling should stop as it might interfere with other user actions.

我不明白如何检测有效或背景使用的应用程序之间的过渡。在onResume()活性的方法似乎并没有帮助,因为一个活动可以隐藏或在主动使用反正可见。我的理解是,应用程序本身并不能使2国之间的差异。 当pressed HOME键能不能有关系吗?是否有另一种方式做区分? 我想到的是iPhone的应用程序的委托方法等效的 applicationDidEnterBackground 。是不是正确的方式去思考与Android?或者,我应该用另一种方法?

I don't understand how to detect the transition between the "active" or "background" use of the app. The onResume() activity methods does not seem to help, as an activity can be hidden or visible during "active" use anyway. My understanding is that the app itself doesn't make the difference between the 2 states. Can it be related when the HOME button is pressed ? Is there another way to do the distinction ? I am thinking of an equivalent of iPhone's app delegate method applicationDidEnterBackground. Is it the right way to think with Android ? Or shall I use another approach ?

感谢你。

推荐答案

我要引用的 活动生命周期。在这两者之间 onResume 的onPause 活动是主动即,它是在屏幕上,用户可以用它进行交互。如果您的活动的的onPause 方法被调用,那么你应该认为它不再是积极的,并且用户无法与之交互了,直到 onResume 再次调用。如果你想跟踪这在服务你将不得不手动执行此操作。

I'm going to reference the Activity Lifecycle. In between onResume and onPause your Activity is 'active', i.e., it's on the screen and the user can interact with it. If your activity's onPause method is called then you should assume that it is no longer 'active' and the user cannot interact with it anymore until onResume is called again. If you wish to track this in your service you're going to have to do this manually.

这大概是最容易实现的,通过调用你的服务的方法在活动#onResume 递增计数器或设置一个标志,并在的onPause 恢复这种变化。如果您有多个活动,那么你很可能会需要一个计数器,可能是一个的AtomicInteger ,并用它来确定什么时候你应该恢复您的投票。

This is probably most easily achieved by calling a method in your service in Activity#onResume that increments a counter or sets a flag and in onPause reverting that change. If you have multiple activities then you're most likely going to need a counter, probably an AtomicInteger, and use it to determine when you should resume your polling.

我可能会等待一段小一点,当计数器为0时,重新检查它,如果它仍然是0简历投票。这将占到之间的一个活动的的onPause 和另外的 onResume

I would probably wait for a small bit of time when the counter reaches 0, recheck it, and if it is still 0 resume polling. This would account for the gap between one activity's onPause and another's onResume.