【问题标题】:Update location in background?在后台更新位置?
【发布时间】:2020-08-12 14:34:57
【问题描述】:

我想在后台更新用户的位置。

为了在后台执行任务,我使用了这个包 workmanager。 链接:https://pub.dev/packages/workmanager

但我无法更新位置,似乎无法使用异步代码?

这是我的代码,

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    await _HomeScreenState().updateUserLoc();
    print('it is working?');

    return Future.value(true);
  });
}
//Inside my stateFul Widget,



 void initState() {
    super.initState();
  
    
    Workmanager.initialize(
      callbackDispatcher,
      isInDebugMode: true,
    );

    Workmanager.registerPeriodicTask(
      "1",
      fetchBackground,
      frequency: Duration(minutes: 15),
    );
  }


updateUserLoc() async {
    print("executi9ng the updateUserLocccccc");
    await getusersLocation();
    print("executi9ng the updateUserLoc");
    GeoFirePoint point = geo.point(latitude: lat, longitude: long);
    _firestore.collection('locations').document(widget.userid).setData(
      {'position': point.data},
      merge: true,
    );
  }

有没有其他方法可以在后台更新用户的位置?

【问题讨论】:

    标签: android firebase flutter dart


    【解决方案1】:

    您必须直接在callbackDispatcher 中调用updateUserLoc() 中的代码。只需将 callbackDispatcher 设为异步函数即可。

    【讨论】:

    • 但是,为了实现这一点,我必须将我的大部分代码移到类之上(..使其成为顶级),这是一个好习惯吗?
    • 您可以将 callbackDIspatcher 函数本身放在您想要放置 updateUserLoc() 的类中。请记住将其设为顶级函数并将文件 i 导入到您正在调用 workmanager.initialize 的文件中。
    • 我喜欢使用 workmanager callbackDispatchers 的方式是创建一个单独的后台服务类,并将所有类似的函数保存在该文件中。
    猜你喜欢
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多