GPS
Getting Started
Xamarin Essentials is great, but Shiny makes realtime background location updates a thing on Xamarin/MAUI based platform.
Setup
Starting/Stopping the GPS Service
IGpsManager gpsManager; // injected, resolved, etcawait gpsManager.StartListener(new GpsRequest{ UseBackground = true});
gpsManager.StopListening();
Observing in the background
First, create the delegate that implements IGpsDelegate
public partial class MyGpsDelegate : Shiny.Locations.IGpsDelegate{ public MyGpsDelegate() { // like all other shiny delegates, dependency injection works here // treat this as a singleton }
public Task OnReading(IGpsReading reading) { // do something with the reading }}
Controlling GPS Notification on Android
#if ANDROIDpublic partial class MyGpsDelegate : Shiny.IAndroidForegroundServiceDelegate{ public void ConfigureNotification(AndroidX.Core.App.NotificationCompat.Builder builder) { builder .SetContentTitle("MyApp") .SetContentText("My App is following you!! images") .SetSmallIcon(Resource.Mipmap.youricon); }}#endif
Next, let’s register that with your app builder/hosting/service collection
services.UseGps<MyGpsDelegate>();
Lastly, last start it up
IGpsManager gpsManager; // injected, resolved, etcawait gpsManager.StartListener(new GpsRequest{ UseBackground = true});
Easier Delegate
The platform mechanics don’t always play by the rules for time & distance filters that you may expect especially with a more ‘real time’ setup.
To work around these issues, you can use the GpsDelegate
class which will handle the filtering for you.
public class MyGpsDelegate : GpsDelegate{ public MyGpsDelegate(ILogger<MyGpsDelegate> logger) : base(logger) { // if either of these filters pass, the OnGpsReading method will be called this.MinimumDistance = Distance.FromMeters(200); this.MinimumTime = TimeSpan.FromMinutes(1); }
protected override async Task OnGpsReading(GpsReading reading) {
}}