See also https://flutter.io/flutter-for-android/#how-do-i-listen-to-android-activity-lifecycle-events
You can listen for inactive, paused, and detached.
This might be a bit too early but usually, it’s better to do some cleanup a bit too early and too often than not at all:
WidgetsBinding.instance.addObserver(LifecycleEventHandler(
detachedCallBack: () async => widget.appController.persistState(),
resumeCallBack: () async {
_log.finest('resume...');
}));
class LifecycleEventHandler extends WidgetsBindingObserver {
LifecycleEventHandler({this.resumeCallBack, this.detachedCallBack});
final FutureVoidCallback resumeCallBack;
final FutureVoidCallback detachedCallBack;
// @override
// Future<bool> didPopRoute()
// @override
// void didHaveMemoryPressure()
@override
Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
switch (state) {
case AppLifecycleState.inactive:
case AppLifecycleState.paused:
case AppLifecycleState.detached:
await detachedCallBack();
break;
case AppLifecycleState.resumed:
await resumeCallBack();
break;
}
_log.finest('''
=============================================================
$state
=============================================================
''');
}
// @override
// void didChangeLocale(Locale locale)
// @override
// void didChangeTextScaleFactor()
// @override
// void didChangeMetrics();
// @override
// Future<bool> didPushRoute(String route)
}
Edit
With this pull request on 4th November 2019, the enum AppLifecycleState.suspending
was renamed to AppLifecycleState.detached
. If you are using Flutter with a version prior to 1.12, you must still use AppLifecycleState.suspending
.