michael-cheung-thebus / foreground_service

Other
43 stars 29 forks source link

Run Function just Once option #32

Open cormalenv opened 4 years ago

cormalenv commented 4 years ago

Hi @michael-cheung-thebus

How do we run a function, particularly those of longer duration, in a foreground service just once without repeating? In native this is fairly straightforward. I am unable to implement the same here. I must be missing something but cannot find any references in the documentation.

I currently use ForegroundService in native to run a long function until completion at which point the FGS is stopped. I also use it to run a location provider, which remains active until the user has finished with the provider and service and then actively stops both.

All options I have tried are attempts to workaround the interval and failed . These include setting the interval to an arbitrarily large period say '999999' seconds and stopping at will. The problem being if the user needs to restart the service, which is of course possible and works OK, the function itself will not run again until 999999s have passed from the previous service. If I leave out the interval and stop the service, the function is called at least once more depending on the duration of the function. I can only get it to work if I set the interval slightly longer than the function run duration, thereby allowing the service to stop properly before the next function is called. In the real world the duration is not set however.

These are all workarounds to the interval requirement. There must be a simple way to just run once I have missed.

cormalenv commented 4 years ago

I just found await ForegroundService.setServiceFunctionAsync(false); in source code which prevents the next function trigger until the first is complete. So for a single run of code, however long, the work around is to have the function call stopService when complete.

Still seems like a workaround. I'm also not sure how this works with say a location provider waiting for a callback.

TheLastGimbus commented 4 years ago

~For me, setting this to false makes my function not run at all!~ Edit: Sorry, turns out it was my falut :P It does not But yeah, I would like such functionality too. I want a Foreground Serivce because I want it to persist, not reset all the times!

easazade commented 3 years ago

have you found any solutions?

TheLastGimbus commented 3 years ago

@easazade right now, not-letting your function finish is probably only way. Altough I didn't touch this for a while