1

We have an Android app that periodically polls for data and updates the display. The polling is performed by a background thread. Unfortunately, this background thread constantly runs, even when our app is offscreen or when the device is locked, which leads to unnecessary network activity and CPU/battery usage.

So, I would like to change the app such that it will suspend its polling activities in these cases:

  • When none of the application's activities are in the foreground.
  • When the device is locked.

What is the easiest way to detect whether the app is in either of these states?

Note: The app has several activities, so I don't think it is as simple as just keeping track of the activity lifecycle events. I would have to add code to each activity to keep track of whether any of my activities are in the foreground. If that's what I need to do, I'll do it, but I'm hoping there is a simpler way.


These are some questions which are related, but which don't seem to provide a good answer:

Community
  • 1
  • 1
Kristopher Johnson
  • 81,409
  • 55
  • 245
  • 302

2 Answers2

4

What is the easiest way to detect whether the app is in either of these states?

For the are-we-in-the-foreground issue, increment a reference count in a static data member in onStart() of each activity, and decrement it in onStop(). If onStop() sees 0, stop the polling. If onStart() sees that you're not polling, start polling.

For the is-the-screen-locked issue, don't worry about it. The device will fall asleep once the screen times out and your polling thread will not be running. Besides, I think your activity will be stopped in this case anyway.

BTW, this is one case where onStop() is the right answer, not onPause(), so the lifecycle handoff between your activities is handled properly.

If that's what I need to do, I'll do it, but I'm hoping there is a simpler way.

That's as simple as it gets.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
1

My intuition says that says that you're thinking about this wrong. You're right to think that you need to curtail your polling when not necessary, but how about just not polling at all? You could use a push paradigm instead (see long polling or Android Cloud To Device Messaging). If your doing this polling to keep resources in sync, you might also want to checkout the android SyncAdapter.

Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
  • We are pulling data from web services. It would be non-trivial to make changes to the server-side stuff. – Kristopher Johnson Oct 26 '11 at 17:10
  • 1
    Ah, ok. Fair enough. Then you should probably go with the SyncAdapter and set it to autosync at the interval you want. The SyncManager should take care of turning it off when necessary. – Kurtis Nusbaum Oct 26 '11 at 17:14
  • Thanks. I'll look into SyncAdapter, but my initial impression is that changing our existing code to use it would be more work than we want to do. – Kristopher Johnson Oct 26 '11 at 17:21