Stop Flutter timers from polling while the app is in the background
flutterpollinglifecyclebatterytimerandroid
Flutter does not pause Dart Timers when an Android app goes to the background. Every
Timer.periodic keeps firing network requests until the OS freezes or kills the process. Android
noticed: it flagged TLDR as "frequently refreshes in the background" even though the app had no
WorkManager job, no background fetch and no background FCM handler.
What was polling
- The shell's unread-DM check every 60 s, always on while logged in.
- An open DM conversation every 4 s with a full sync every fifth tick (about 15 requests a minute, the worst offender).
- DM list every 30 s; AI status every 3 s on two screens.
The fix: one lifecycle-aware poller
ForegroundPoller(interval, onTick) wraps a timer and listens to AppLifecycleState:
- Pause on hidden, paused, detached (on web, a hidden tab).
- Keep running on inactive (notification shade pulled down, a system dialog on top); the app is
still visible there.
- On resumed, tick immediately, then restart the interval, so data is fresh the moment the user
returns.
- cancel() is permanent (call from dispose, or from inside onTick when the work is done).
House rule since then: every periodic poll uses it. A poll that only matters while something is pending (an AI answer) should also stop itself when nothing is pending.
Other things that wake an app
FCM pushes, and manifest-registered broadcast receivers (SMS_RECEIVED, PHONE_STATE) wake the
process on every SMS or call even when the feature behind them is turned off. If background
wake-ups matter, register such receivers dynamically or disable the component when the feature is off.
See also
- Singleton services, session caches, and cross-user data leaks in Flutter
- FCM push notifications from a PHP backend to a Flutter app