I am using the following code for calling a function every 10 seconds.
var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromSeconds(10);
var timer = new System.Threading.Timer((e) =>
{
MyFunction();
}, null, startTimeSpan, periodTimeSpan);
MyFunction()
will execute every 10 seconds when the app is on the open state. When the app is in the background, that function is not invoking.
So how can I invoke a function when the app is in the background? Are there any NuGet packages for this or we need to do this using the dependency service?
UPDATE
When I running your demo I am getting the below exception:
I have integrated the codes on my sample. The code execution coming on Start()
in the StartServiceDroid
. But not hitting the OnStartCommand()
function. Here is my sample, could you please have a look? I need to run the MyFunction()
every x seconds in the background or foreground mode.
Update 10-07-2020
@Leon Lu - MSFT I found a new solution here. :)
var second = TimeSpan.FromSeconds(10);
Device.StartTimer(second, () => {
Debug.WriteLine("Hiiiii");
return true;
});
I create a sample application with this code and it is working fine on foreground and background mode. Every 10 seconds, the Hiii message is printing on the output box even the app is running on the background.
This is included with Xamarin Forms, so no need for any platform-specific logic.
Is there any problem with this approach?
Update 15/07/2020
Today I have tested it on a real device. :)
Case 1: Run the app on Visual Studio, Service is invoking in foreground mode. Move the app to the background (Still, the app is running in VS), the background service is invoking when the app is on the background every 10 seconds.
Case 2: Open the app installed app normally, (not running it in VS), service is invoking in foreground mode, Move the app to the background, the background service is not invoking even after 10minutes.
I am totally confused now, background service is invoking when the app is running on VS and not invoking when open the installed app normally. For the second case, I have waited for more than 10 minutes, but the service that I added is not invoking. Both cases are done on debug mode.
Is it the only behavior of xamarin forms platform? If we do it in the native ios platform, is it possible to trigger the background service on every x seconds? How skype is doing background service?
Tested device model: iPhone 7 Software version: 13.5.1