Workmanager().registerPeriodicTask doesn't work on app terminated/app kill
I have workmanager to call function to get user location and send it to API. This location task is working fine in the foreground but not working when app is terminated.
@pragma('vm:entry-point')
void callbackDispatcher() {
Workmanager().executeTask((task, inputData) async {
if (task == 'locationTask') {
try {
Position position = await getUserLocation();
await doCheckin(position);
} catch (e) {
print("bg docheckin failed with $e");
}
}
return Future.value(true);
});
}
Future<Position> getUserLocation() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high,
);
return position;
}
doCheckin(Position position) async {
//getuser location
// get user ID from Shared Preferences
SharedPreferences prefs = await SharedPreferences.getInstance();
String? userId = prefs.getString('userID');
String? companyCode = prefs.getString('companyCode');
String? employeeNo = prefs.getString('employeeNo');
final value = prefs.get('token') ?? 0;
// send user ID to API
Map<String, dynamic> data = {
'userID': userId,
'companyCode': companyCode,
'employeeNo': employeeNo,
'longitude': position.longitude,
'latitude': position.latitude
};
Map<String, String> headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer $value',
};
http.Response response = await http.post(
Uri.parse('$baseURL/CheckIn/doCheckIn'),
headers: headers,
body: json.encode(data));
if (response.statusCode == 200) {
print('success');
} else {
print('failed: ${response.body}');
}
}
on main()
WidgetsFlutterBinding.ensureInitialized();
Workmanager().initialize(
callbackDispatcher,
isInDebugMode: true,
);
Workmanager().registerPeriodicTask(
'locationTask',
'locationTask',
frequency: Duration(minutes: 15),
constraints: Constraints(
networkType: NetworkType.connected,
requiresBatteryNotLow: true,
requiresCharging: false,
requiresDeviceIdle: false,
requiresStorageNotLow: true,
),
initialDelay: Duration(seconds: 30),
backoffPolicy: BackoffPolicy.linear,
backoffPolicyDelay: Duration(seconds: 10),
);
runApp(const MyApp());
Update
I comment the getLocation function, workmanager running normally even app is terminated.
//Position position = await getUserLocation();
//await doCheckin(position);
So, is not posible to get user location using geolocator in app terminated?
Update
I comment the getLocation function, workmanager running normally even app is terminated.
//Position position = await getUserLocation(); //await doCheckin(position);So, is not posible to get user location using
geolocatorin app terminated?
I think you should change the AppDelegate.swift to support the usage of plugin as mentioned here
App termination means all background tasks are cleared and stopped as well. There is not much work manager can do. You could try sending a push notification from remote in order to wake up the app, just be aware this may have caveats as well