如何在flutter IOS中每15分钟在后台运行一次workmanager

mar*_*wan 5 flutter

我正在为我的项目添加一个 workmanager 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),
    );
  }



Run Code Online (Sandbox Code Playgroud)

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

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

Run Code Online (Sandbox Code Playgroud)

在这种情况下,该应用程序适用于我而不使用 registerPeriodicTask,但我必须运行 Debug ?手动模拟后台获取以从 XCode 获取警报。那么有什么办法可以让应用在iOS和Android后台每15分钟运行一次呢?

Muh*_*fay 5

因此,ansyns timer如果应用程序正在运行,无论当前打开哪个屏幕,您都可以使用每 15 秒调用一次的方法来代替此方法。

所以你可以在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();
Run Code Online (Sandbox Code Playgroud)