Reputation: 415
I'm writing an app that will send location data every x seconds, and run in the background. I'm calling the following method.
public void StartListening()
{
UpdateGpsService();
if(CLLocationManager.LocationServicesEnabled)
{
locationManager.DesiredAccuracy = 10;
nint taskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
timer = new Timer((o) =>
{
CLLocation location = locationManager.Location;
Nmea nmea = new IOSNmea(location);
Gprmc gprmc = new Gprmc();
gprmc.url = this.Url;
gprmc.Id = this.DeviceId;
gprmc.GprmcString = nmea.ToString();
}, null, 0, UpdateInterval * 1000);
});
App.Database.SaveItemAsync(new TodoItem() { key = LOCATOR_SERVICE_ID, value = taskId.ToString() });
}
}
However, it doesn't seem to be calling the code inside the timer callback. I tried putting a breakpoint in there, and it never gets called. Is there something obviously wrong with my code? Thanks for any help.
Upvotes: 0
Views: 151
Reputation: 74209
BeginBackgroundTask
only tells iOS that you are starting a long running task and the handler is not for the execution of that task, BUT it is a completion handler that is called when the OS is about to shut it down...
Timer timer = null;
nint taskId = UIApplication.SharedApplication.BeginBackgroundTask(() =>
{
// Clean up as the background task is begin shutdown by iOS
timer?.Dispose();
});
timer = new Timer((o) =>
{
Console.WriteLine("Timer Update");
}, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
// Must call EndBackgroundTask when you are done with this...
// UIApplication.SharedApplication.EndBackgroundTask(taskId);
Upvotes: 1