Dev-hwang / flutter_foreground_task

This plugin is used to implement a foreground service on the Android platform.
https://pub.dev/packages/flutter_foreground_task
MIT License
149 stars 109 forks source link

Feature Request: Add onServiceRestarted method #276

Closed TheValkDokk closed 1 month ago

TheValkDokk commented 1 month ago

Hi, i don't know if the onStart method of TaskHandler will be called whenever the Background task is restarted or not, so adding a specific method to know when the service is killed then restarted by Alarm Manager (Android) would be very useful. for cases like loading data to resume operations before the service is killed

Also a few more question:

Your answer would helps a lot, Thanks in advance

Dev-hwang commented 1 month ago

@TheValkDokk

I'm not very good English, so I'm not sure if I understood it correctly.

Is there anyway to test and kill the service and test it in debug mode ?

No. Currently, this plugin cannot test forcibly killing the service in debug mode.

It seem that i can't do asynchronous functions in the onDestroy, is that the expected behavior

I didn't understand this question. I would appreciate it if you could provide an example or expected scenario.


I think good idea to add the onServiceRestarted function. Because different processing may be required depending on whether onStart was called in normal way or onStart was called when the service was restarted by OS or Alarm Manager. I will add this function in the next version.

TheValkDokk commented 1 month ago

Hi, about the second question: onDestroy, what i means is when onDestroyed is called, operations like:

  void onDestroy(DateTime timestamp) async {
    print('onDestroy');
    await saveStateToLocal();
  }

I will test make these method calls without await and check their behavior, thanks for consider adding onServiceRestarted

Dev-hwang commented 1 month ago

@TheValkDokk

This seems to be because the Flutter engine is destroyed as soon as onDestroy is called.

I will try to solve this issue by returning a Future in onDestroy.

Thank you for reporting the issue.

Dev-hwang commented 1 month ago

@TheValkDokk

please update to the latest version.

you can check whether the task has been restarted by the OS using the starter parameter of the onStart callback.

@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {
  if (starter == TaskStarter.system) {
    // restarted by the OS
  }

  if (starter == TaskStarter.developer) {
    // restarted by the developer
  }
}

also, you can access network, database, and other plugins in onDestroy callback. :blush:

@override
Future<void> onDestroy(DateTime timestamp) async {
  await saveStateToLocal();
}