Skip to content

Commit

Permalink
Geolocation - Location Updates xamarin#290 - added ContinuousLocation…
Browse files Browse the repository at this point in the history
…Listener ported from Geolocator.Plugin.GeolocationContinuousListener
  • Loading branch information
alexreich committed Dec 27, 2019
1 parent a719d90 commit 7c043df
Showing 1 changed file with 87 additions and 0 deletions.
87 changes: 87 additions & 0 deletions Xamarin.Essentials/Geolocation/Geolocation.android.cs
Original file line number Diff line number Diff line change
Expand Up @@ -271,4 +271,91 @@ void ILocationListener.OnStatusChanged(string provider, [GeneratedEnum] Availabi
}
}
}

class ContinuousLocationListener : Java.Lang.Object, ILocationListener
{
readonly HashSet<string> activeProviders = new HashSet<string>();
readonly LocationManager manager;
IList<string> providers;

string activeProvider;
AndroidLocation lastLocation;
TimeSpan timePeriod;

public ContinuousLocationListener(LocationManager manager, TimeSpan timePeriod, IList<string> providers)
{
this.manager = manager;
this.timePeriod = timePeriod;
this.providers = providers;

foreach (var p in providers)
{
if (manager.IsProviderEnabled(p))
activeProviders.Add(p);
}
}

internal Action<AndroidLocation> LocationHandler { get; set; }

void ILocationListener.OnLocationChanged(AndroidLocation location)
{
if (location.Provider != activeProvider)
{
if (activeProvider != null && manager.IsProviderEnabled(activeProvider))
{
var pr = manager.GetProvider(location.Provider);
var lapsed = GetTimeSpan(location.Time) - GetTimeSpan(lastLocation.Time);

if (pr.Accuracy > manager.GetProvider(activeProvider).Accuracy
&& lapsed < timePeriod.Add(timePeriod))
{
location.Dispose();
return;
}
}

activeProvider = location.Provider;
}

var previous = Interlocked.Exchange(ref lastLocation, location);
if (previous != null)
previous.Dispose();

LocationHandler?.Invoke(location);
}

public void OnProviderDisabled(string provider)
{
lock (activeProviders)
activeProviders.Remove(provider);
}

public void OnProviderEnabled(string provider)
{
if (provider == LocationManager.PassiveProvider)
return;

lock (activeProviders)
activeProviders.Add(provider);
}

public void OnStatusChanged(string provider, Availability status, Bundle extras)
{
switch (status)
{
case Availability.Available:
OnProviderEnabled(provider);
break;

case Availability.OutOfService:
OnProviderDisabled(provider);
break;
}
}

TimeSpan GetTimeSpan(long time)
{
return new TimeSpan(TimeSpan.TicksPerMillisecond * time);
}
}
}

0 comments on commit 7c043df

Please sign in to comment.