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.
You can detect currently foreground/background application with ActivityManager. getRunningAppProcesses() which returns a list of RunningAppProcessInfo records. To determine if your application is on the foreground check RunningAppProcessInfo.
The onPause() and onResume() methods are called when the application is brought to the background and into the foreground again. However, they are also called when the application is started for the first time and before it is killed. You can read more in Activity.
An app is running in the background when both the following conditions are satisfied: None of the app's activities are currently visible to the user. The app isn't running any foreground services that started while an activity from the app was visible to the user.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With