【发布时间】:2018-08-29 09:39:55
【问题描述】:
我想知道检测是否可以关闭应用程序。
假设在一个聊天应用程序中,当用户离开聊天室时,我可以使用 onWillPop 获取时间戳。
但是,如果用户直接从聊天室中关闭应用程序,它不会被解雇。那么有没有办法检测到呢?
或者有什么建议以不同的方式获取时间戳?
【问题讨论】:
标签: flutter
我想知道检测是否可以关闭应用程序。
假设在一个聊天应用程序中,当用户离开聊天室时,我可以使用 onWillPop 获取时间戳。
但是,如果用户直接从聊天室中关闭应用程序,它不会被解雇。那么有没有办法检测到呢?
或者有什么建议以不同的方式获取时间戳?
【问题讨论】:
标签: flutter
另见https://flutter.io/flutter-for-android/#how-do-i-listen-to-android-activity-lifecycle-events
您可以监听非活动、暂停和分离。 这可能有点太早了,但通常做一些清理工作有点太早和太频繁总比根本不做要好:
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)
}
编辑
在 2019 年 11 月 4 日,有了这个 pull request,枚举 AppLifecycleState.suspending 被重命名为 AppLifecycleState.detached。如果你使用 Flutter 1.12 之前的版本,你仍然必须使用AppLifecycleState.suspending。
【讨论】: