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.
I'm going to reference the
Activity
Lifecycle. In betweenonResume
andonPause
yourActivity
is 'active', i.e., it's on the screen and the user can interact with it. If your activity'sonPause
method is called then you should assume that it is no longer 'active' and the user cannot interact with it anymore untilonResume
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 inonPause
reverting that change. If you have multiple activities then you're most likely going to need a counter, probably anAtomicInteger
, 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'sonResume
.