2

I am developing a Flutter app that is meant to be used to control IoT devices that are connected to the local network.

Unfortunately, while testing the app, I have experienced the following issue: According to the iOS settings app, the app is responsible for a large percentage of the current battery drain, even when the screen time is low. In other words, the app is draining the phone's battery while it is running in the background.

I have done some research on the issue and came to the conclusion that Flutter apps are meant to be suspended when the user returns to the Home Screen or switches to a different app. In fact, there are countless articles that describe ways to still execute code even after the app has been suspended.

This does not seem to be the case for me. For testing purposes, I have created a periodic timer that prints a message any time a second passes. I am also listening to app life cycle state changes via the WidgetsBindingObserver. This is the output I am getting:

terminal screenshot

As you can see, the timer is still active even after the app has been paused (by means of me pressing the Home button).

Is there a way to properly suspend the app when the user sends it to the background?

Technical info:

Flutter Doctor output:

[✓] Flutter (Channel stable, 2.2.0, on macOS 11.3.1 20E241 darwin-arm, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS
[✗] Chrome - develop for the web (Cannot find Chrome executable at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.
[✓] Android Studio (version 4.1)
[✓] VS Code (version 1.56.2)
[✓] Connected device (2 available)

! Doctor found issues in 1 category.

The console output was generated on an iPhone 8 running iOS 14.4, however I have observed the issue on Android as well.

Thanks in advance, ThePC007.

ThePC007
  • 41
  • 5

1 Answers1

0

on your Widget override the dispose method as follows.

@override
  void dispose() {
    timer.cancel();
    super.dispose();
  }

this will cancel the timer when your app in the background

Lakmal Fernando
  • 1,420
  • 6
  • 14
  • It doesn't seem like a widget's dispose function is called when the app is suspended, as this did not actually fix the issue. Either way, I could, of course, cancel all my timers when the life cycle state changes to `AppLifecycleState.paused`, however I believe the issue may lie somewhere else, considering that the app is still running even when (from what I can find), it really shouldn't. I'm afraid the energy consumption may still remain high even after canceling all timers. – ThePC007 May 28 '21 at 12:56
  • It's ironic that so many people say "how can I keep my app running in the background, like to record my position each second", when they don't realize this will be a battery killer. :) – Randal Schwartz May 29 '21 at 16:55