views:

59

answers:

1

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.

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 ?

Thank you.

+1  A: 

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.

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.

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.

Qberticus
I finally did it only on the root activity : as soon as the root activity disappears ( either because app is left or because a subsequent activity covered it ), I trigger the service. As you adviced, I then trigger a timer, and then start polling. If the root activity re-appears before the timer expires, service is stopped. I tick your answer as it helped me anyway, thanks.