【问题标题】:Flutter | how can i record the time user spend in my app in flutter?颤振 |我如何记录用户在我的应用程序中花费的时间?
【发布时间】:2021-01-22 12:31:32
【问题描述】:

我已开发应用程序,客户希望我存储用户在应用程序内花费的总时间 我怎样才能做到这一点 我曾尝试在颤振中使用this App_usage package,但它向我显示 Star Activity 错误 如果你们有任何解决方案
请告诉我 在此先感谢:)

【问题讨论】:

标签: flutter flutter-layout flutter-dependencies flutter-animation flutter-test


【解决方案1】:

就像 Chris Marx 所说,您可以使用计数器来存储使用时间。为了处理与服务器的同步操作,您可以使用共享首选项来存储数据,并在应用再次启动时与服务器进行同步(更新)。

【讨论】:

【解决方案2】:

有一些变量来跟踪应用程序的开始时间和结束/暂停时间并保持差异。您必须将其连接到应用程序生命周期才能监听诸如暂停/恢复应用程序之类的事件。 (例如How to handle onPause/onResume in Flutter App?

类似这样的:

class AppLifecycleReactor extends StatefulWidget {
  const AppLifecycleReactor({Key key}) : super(key: key);

  @override
  _AppLifecycleReactorState createState() => _AppLifecycleReactorState();
}

class _AppLifecycleReactorState extends State<AppLifecycleReactor>
    with WidgetsBindingObserver {
  DateTime startTime;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      startTime = DateTime.now();
    }

    if (state == AppLifecycleState.detached ||
        state == AppLifecycleState.paused) {
      var usageTime = DateTime.now().difference(startTime);
      // do whatever with the usageTime
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: MyContent(),
    );
  }
}

【讨论】:

  • 嘿,谢谢,但我不这样做,因为看到恢复和暂停是应用程序的中间过程我想要的是当用户进入应用程序时,计时器应该启动以及应用程序获取时关闭 [未暂停] 然后计时器应该停止并保存最近的值,因此您有什么建议或计划或任何会很有帮助的东西
  • 您只能使用 AppLifecycleState.detached 但您必须以不同的方式处理 startTime 的设置,因为 AppLifecycleState.resumed 将通过启动或恢复应用程序来触发。您可以在您的根小部件 init 方法中将其输出。
  • 嘿兄弟感谢您的帮助,在此之后我面临新问题,即当应用程序处于分离或非活动状态时,它无法进行 api 调用,是无法完成还是可以完成谢谢提前:)
  • Future updateTimer() async { 进行 http 调用 ... } 覆盖 Future didChangeAppLifecycleState(AppLifecycleState state) async { SharedPreferences prefs = await SharedPreferences.getInstance(); if (state.toString() == "AppLifecycleState.detached") { var _hours, _minutes; _hours = prefs.getInt("小时"); _minutes = var ttoken =.., ;var uuserId =..; // 正在调用此函数,但未执行 api 调用 await updateTimer(_hours, _minutes, ttoken, uuserId);打印(是); } }
  • 我现在或多或少在猜测,但我想说的是,当应用程序将要分离/不活动时,您不能进行异步调用,因为调用可能需要更长的时间并且应用程序将,如前所述,处于非活动状态且无法响应。您可以尝试在 on resume 方法中处理它。还有一些提示:1. 您不需要 state.toString() == "AppLifecycleState.detached" state == AppLifecycleState.detached 工作和 2. 您应该将时间保留为以毫秒或秒为单位的单个数字(unix 时间),而不是分别保存小时和分钟。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-22
  • 2020-06-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多