flutter_workmanager icon indicating copy to clipboard operation
flutter_workmanager copied to clipboard

Workmanager().registerPeriodicTask doesn't work on app terminated/app kill

Open alwangk opened this issue 3 years ago • 3 comments

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());
Screen Shot 2023-03-06 at 15 23 51

alwangk avatar Mar 06 '23 08:03 alwangk

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?

alwangk avatar Mar 07 '23 03:03 alwangk

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?

I think you should change the AppDelegate.swift to support the usage of plugin as mentioned here

kekko7072 avatar Apr 25 '23 09:04 kekko7072

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

ened avatar Apr 27 '23 09:04 ened