如何在抖动的IOS中每15分钟在后台运行一次Workmanager

时间:2020-11-06 11:07:27

标签: flutter

我正在为我的项目添加一个工作人员管理工具。现在,它可以在Android系统上完美运行,如下所示:

const fetchBackground = "fetchBackground";

void callbackDispatcher() {
  Workmanager.executeTask((task, inputData) async {
    switch (task) {
      case fetchBackground:
        Position userLocation = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
        notif.Notification notification = new notif.Notification();
        notification.showNotificationWithoutSound(userLocation);
        break;
    }
    return Future.value(true);
  });
}



void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  @override
  void initState() {
    super.initState();

    Workmanager.initialize(
      callbackDispatcher,
      isInDebugMode: true,
    );


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



因此,现在每15分钟,该应用程序将在下面的后台运行,并向用户发送完美警报。但是对于IOS,我不能使用:registerPeriodicTask。

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

在这种情况下,该应用程序无需使用registerPeriodicTask就可以为我工作,但是我必须手动运行“调试”→“模拟后台提取”才能从XCode获取警报。那么,使该应用程序在iOS和Android中每15分钟在后台运行一次的解决方案是什么

2 个答案:

答案 0 :(得分:1)

因此,无论当前打开的是什么屏幕,只要运行该应用,您都可以使用每15秒调用一次的ansyns timer

因此您可以在main.dart文件中调用它

Timer timerObj;
    timerObj = Timer.periodic(Duration(seconds: 15), (timer) async {
          _initData();
         
          }
        });
    
    In order to cancel the timer you can call timerObj = null or timerObj.cancel();

答案 1 :(得分:0)

为了在 iOS 中执行后台获取,只需在 AppDelegate.swift 中的 didFinishLaunchingWithOptions 中添加这一行 UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*15))

参考:https://github.com/fluttercommunity/flutter_workmanager/blob/master/IOS_SETUP.md