Created
May 29, 2017 21:05
-
-
Save ericbrunner/950323935282ca0f563e21d764762080 to your computer and use it in GitHub Desktop.
GpsTrackerService
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Service] | |
public class GpsTrackerService : Service | |
{ | |
bool _isStarted; | |
static readonly int TimerWait = 60000; // every 60 seconds | |
Timer _timer; | |
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId) | |
{ | |
if (!_isStarted) | |
{ | |
_timer = new Timer(HandleTimerCallback, null, 0, TimerWait); | |
_isStarted = true; | |
MetricsManagerHelper.Instance.SendGenericMessageToApplicationInsights("Gps-Info", "Timer started."); | |
} | |
return StartCommandResult.Sticky; | |
} | |
public void HandleTimerCallback(object state) | |
{ | |
if (CrossConnectivity.Current.IsConnected) | |
{ | |
Task.Run(async () => | |
{ | |
TruckFahrerGeoData truckFahrerGeoData = new TruckFahrerGeoData(); | |
try | |
{ | |
var locator = CrossGeolocator.Current; | |
locator.DesiredAccuracy = 10; | |
// Timeout 5 seconds | |
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10)); | |
await GeoLocationDataManager.Instance.PersistGeoLocationData(position, truckFahrerGeoData); | |
} | |
catch (Exception e) | |
{ | |
Dictionary<string, string> telemetryDictionary = new Dictionary<string, string>(); | |
var serializedGeoData = JsonConvert.SerializeObject(truckFahrerGeoData); | |
telemetryDictionary.Add("TruckFahrerGeoData", serializedGeoData); | |
await MetricsManagerHelper.Instance.SendGenericMessageToApplicationInsightsAsync("Gps-Error", e.Message, telemetryDictionary); | |
} | |
}); | |
} | |
} | |
public override IBinder OnBind(Intent intent) | |
{ | |
// This is a started service, not a bound service, so we just return null. | |
return null; | |
} | |
public override void OnDestroy() | |
{ | |
_timer.Dispose(); | |
_timer = null; | |
_isStarted = false; | |
MetricsManagerHelper.Instance.SendGenericMessageToApplicationInsights("Gps-Info", "Timer disposed."); | |
base.OnDestroy(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment