I am working on adding a workmanager flutter to my project. Now it works perfectly on Android system as follows:
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),
);
}
So now every 15 minutes, the application will run in the background in the following and send an alert to the user that's perfect. But with IOS I cannot use: registerPeriodicTask.
Workmanager.registerPeriodicTask(
"1",
fetchBackground,
frequency: Duration(minutes: 15),
);
In this case, the app works for me without using registerPeriodicTask, but I have to run Debug → Simulate Background Fetch manually in order to get the alert from XCode. So what is the solution to make the app run every 15 minutes in the background in iOS as well as Android
So instead of this you can use the ansyns timer
that will be called after every 15 seconds if the app is running no matter what screen is currently opened.
So you can call it in the main.dart file
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();
For Executing background fetch in iOS just add this line inside didFinishLaunchingWithOptions inside AppDelegate.swift
UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*15))
For Ref: https://github.com/fluttercommunity/flutter_workmanager/blob/master/IOS_SETUP.md
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With