代码之家  ›  专栏  ›  技术社区  ›  Kris

测量应用程序打开的时间量

  •  0
  • Kris  · 技术社区  · 5 年前

    我试图在应用程序打开十分钟后触发一个事件。有简单的方法吗?我想我需要在应用程序首次构建时启动一个计时器,但如果用户以某种方式离开应用程序,我可以取消或暂停该计时器。

    我找到了 screen state 库,但该库只监听屏幕的关闭和打开,而不监听诸如导航回家或另一个应用程序之类的事件。我很熟悉 WillPopScope ,与我发现的有关 back button interceptor ,但我的理解是,只有当用户按下后退按钮时才会进行拦截,而当用户按下主页或切换到另一个应用程序时则不会。

    是否有某种中心方式可以收听任何会关闭或离开应用程序的内容,或者收听多种内容的组合?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Abion47    5 年前

    开始a Timer 当你 main 方法运行:

    import 'dart:async';
    
    void main() {
      Timer(Duration(minutes: 10), () {
        // Handle the event
      });
    
      runApp(MyApp());
    }
    

    如果你想能够控制计时器,请在根小部件中设置它,并让该小部件监听生命周期事件:

    class MyApp extends StatefulWidget {
      ...
    }
    
    class MyAppState extends State<MyApp> with WidgetsBindingObserver {
      static const _appTimerDuration = const Duration(minutes: 10);
      Timer appTimer;
    
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
        appTimer = Timer(_appTimerDuration, _timerElapsed);
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        appTimer?.cancel();
        super.dispose();
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        if (state == AppLifecycleState.resumed) {
          appTimer = Timer(_appTimerDuration, _timerElapsed);
        } else {
          appTimer?.cancel();
        }
      }
    
      void _timerElapsed() {
        // Handle the event
      }
    
      ...
    }