Skip to content

Instantly share code, notes, and snippets.

@Cheesebaron
Created September 25, 2014 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Cheesebaron/576bdac81c4696a40616 to your computer and use it in GitHub Desktop.
Save Cheesebaron/576bdac81c4696a40616 to your computer and use it in GitHub Desktop.
Random MockLocationSource
using System;
using System.Threading;
using System.Threading.Tasks;
using Android.Gms.Maps;
using Android.Gms.Maps.Model;
using Android.Locations;
using Android.OS;
namespace RunForYourLife
{
public class MockLocationSource : Java.Lang.Object, ILocationSource
{
private readonly Random _random = new Random();
private LatLng _lastCoordinate = _center;
private static readonly LatLng _center = new LatLng(55.784502, 12.525368);
private readonly TimeSpan _updatePeriod = new TimeSpan(0, 0, 0, 2);
private const double DeltaLat = 0.0005;
private const double DeltaLon = 0.0005;
private readonly Handler _handler = new Handler();
private ILocationSourceOnLocationChangedListener _listener;
private CancellationTokenSource _cancellationTokenSource;
private async Task ScheduleNewFix(CancellationToken token)
{
await Task.Delay(_updatePeriod, token).ConfigureAwait(false);
await Task.Run(async () =>
{
try
{
if (token.IsCancellationRequested)
{
token.ThrowIfCancellationRequested();
}
var randomLocation = GenerateRandomLocation();
_handler.Post(() => _listener.OnLocationChanged(randomLocation));
await ScheduleNewFix(token);
}
catch (TaskCanceledException)
{ }
}, token).ConfigureAwait(false);
}
public async void Activate(ILocationSourceOnLocationChangedListener p0)
{
_cancellationTokenSource = new CancellationTokenSource();
_listener = p0;
await ScheduleNewFix(_cancellationTokenSource.Token);
}
public void Deactivate()
{
_cancellationTokenSource.Cancel();
}
public Location GenerateRandomLocation()
{
var location = new Location(typeof (MockLocationSource).Name)
{
Time = DateTime.Now.ToUniversalTime().Millisecond,
Accuracy = 1,
Bearing = _random.Next(360),
Speed = _random.Next(12),
Latitude = _lastCoordinate.Latitude + ScaleOffset(DeltaLat),
Longitude = _lastCoordinate.Longitude + ScaleOffset(DeltaLon)
};
_lastCoordinate = new LatLng(location.Latitude, location.Longitude);
return location;
}
private double ScaleOffset(double value)
{
return (_random.NextDouble() - 0.5) * value;
}
}
}
#if DEBUG
// Generates random Map data
_map.SetLocationSource(new MockLocationSource());
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment