【问题标题】:Flutter detect killing off the appFlutter 检测杀死应用程序
【发布时间】:2018-08-29 09:39:55
【问题描述】:

我想知道检测是否可以关闭应用程序。 假设在一个聊天应用程序中,当用户离开聊天室时,我可以使用 onWillPop 获取时间戳。 但是,如果用户直接从聊天室中关闭应用程序,它不会被解雇。那么有没有办法检测到呢?
或者有什么建议以不同的方式获取时间戳?

【问题讨论】:

    标签: flutter


    【解决方案1】:

    另见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

    【讨论】:

    • 感谢您的评论。所以在我的用例中,我应该听非活动的?
    • 对不起,如果我误解了,只暂停了两个平台的工作。但它说在后台运行。当用户强制退出应用程序时我可以处理这个吗?
    • 我希望这可以工作,但是当应用程序在后台切换或已经显示任务切换器时也会触发,但这通常不会受到伤害,因为你不应该这样做无论如何,这里的工作很昂贵。
    • 好吧,但总比没有好!感谢您一直以来的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    • 2018-12-27
    • 2020-10-23
    相关资源
    最近更新 更多