Flutter 检测关闭应用程序 [英] Flutter detect killing off the app

查看:115
本文介绍了Flutter 检测关闭应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to know whether detect killing off the app is possible or not. Let’s say in a chat app, I was able to get timestamp when user leaves the chat room by using onWillPop. But if user killed off the app directly from the chat room, it won’t be fired off. So is there a way to detect that?
Or any suggestions to get timestamp different way?

推荐答案

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

编辑

通过 2019 年 11 月 4 日的这个 拉取请求,枚举 AppLifecycleState.suspending 重命名为 AppLifecycleState.detached.如果您使用 Flutter 1.12 之前的版本,您仍然必须使用 AppLifecycleState.suspending.

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.

这篇关于Flutter 检测关闭应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆