Reputation: 5375
I'm trying to add a feature to my application that requires obtaining the user's currently location at a set time interval. The issue is that whenever I use System.Threading.Timer
, create a new System.Threading.Thread
and use Thread.Sleep()
, or use NSTimer.CreateScheduledTimer
the application will stop the CLLocationManager
from running when the application is in the background.
LocationManager.cs
public class LocationManager
{
protected CLLocationManager locationManager;
/// <summary>
/// Time in milliseconds between location checking.
/// </summary>
private int serviceMillisecondTimeout = 10000;
public LocationManager()
{
this.locationManager = new CLLocationManager();
// iOS 8 additional permissions requirements
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
locationManager.RequestAlwaysAuthorization();
}
locationManager.LocationsUpdated += onLocationUpdated;
locationManager.DistanceFilter = 1;
locationManager.DesiredAccuracy = 1;
}
public CLLocationManager LManager
{
get { return locationManager; }
}
public void startLocationUpdates()
{
if (CLLocationManager.LocationServicesEnabled)
{
locationManager.StartUpdatingLocation();
}
}
public void stopLocationUpdates()
{
locationManager.StopUpdatingLocation();
}
public void onLocationUpdated(object sender, CLLocationsUpdatedEventArgs e)
{
// stop location updates until timer calls StartUpdatingLocation
locationManager.StopUpdatingLocation();
var coordinate = e.Locations[e.Locations.Length - 1].Coordinate;
double lat = coordinate.Latitude;
double lon = coordinate.Longitude;
// do stuff with coordinates
// This will work until the application goes into the background.
// The same thing seems to happen whenever I try creating
// new threads, or any other form of a timer.
//
// Without any sort of timer or new thread, it will call
// StartUpdatingLocation in the background and will
// continue to run indefinitely.
NSTimer t = NSTimer.CreateScheduledTimer(TimeSpan.FromMilliseconds(serviceMillisecondTimeout), delegate
{
if (CLLocationManager.LocationServicesEnabled)
{
locationManager.StartUpdatingLocation();
}
});
}
}
What can I do to set an explicit time interval and still be able to run location updates in the background?
Upvotes: 2
Views: 1667
Reputation: 3362
This functionality would not be supported by the platform. You can subscribe to significant location changes when in the background or leaving a set geofence but you can not force your code to get a location fix at a specific interval in the background. This is a restriction/limitation of the iOS platform and there is nothing you can do about it.
The closest thing to what you want is maybe Getting Location Events in the Background.
Upvotes: 1