You can use a DependancyService to see if the location is turned on. Some people reading this issue might wonder how to do it on iOS too, so I'll walk you through it.
First, shall we create an interface in the Service folder of our shared code containing:
public interface IGpsDependencyService
{
bool IsGpsTurnedOn();
void OpenSettings();
}
There are two functions here:
- IsGpsTurnedOn(): to check if the GPS is on
- OpenSettings(): to open the location setting page for the user to turn the GPS feature on.
Now we need to craft the native code behind these two functions:
Create GpsDependancyService.cs in a Service folder for both our iOS and Android projects
In the iOS, let's write:
[assembly: Xamarin.Forms.Dependency(typeof(GpsDependencyService))]
namespace YourApp.iOS.Services
{
public class GpsDependencyService : IGpsDependencyService
{
public bool IsGpsTurnedOn()
{
if (CLLocationManager.Status == CLAuthorizationStatus.Denied)
{
return false;
}
else
{
return true;
}
}
public void OpenSettings()
{
var WiFiURL = new NSUrl("prefs:root=WIFI");
if (UIApplication.SharedApplication.CanOpenUrl(WiFiURL))
{ //> Pre iOS 10
UIApplication.SharedApplication.OpenUrl(WiFiURL);
}
else
{ //> iOS 10
UIApplication.SharedApplication.OpenUrl(new NSUrl("App-Prefs:root=WIFI"));
}
}
}
}
Then, for Android, we can write:
[assembly: Xamarin.Forms.Dependency(typeof(GpsDependencyService))]
namespace YourApp.Droid.Services
{
public class GpsDependencyService : IGpsDependencyService
{
public bool IsGpsTurnedOn()
{
LocationManager locationManager = (LocationManager)Android.App.Application.Context.GetSystemService(Context.LocationService);
return locationManager.IsProviderEnabled(LocationManager.GpsProvider);
}
public void OpenSettings()
{
Intent intent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
try
{
Android.App.Application.Context.StartActivity(intent);
}
catch (ActivityNotFoundException activityNotFoundException)
{
System.Diagnostics.Debug.WriteLine(activityNotFoundException.Message);
Android.Widget.Toast.MakeText(Android.App.Application.Context, "Error: Gps Activity", Android.Widget.ToastLength.Short).Show();
}
}
}
}
Now, all we have to do is to call these two functions in our lovely beloved code!
- to use IsGpsTurnedOn(): DependencyService.Get().IsGpsTurnedOn();
- to use OpenSettings(): DependencyService.Get().OpenSettings();
I hope it helps, don't hesitate to ask me questions in the comment
Source: https://github.com/xamarin/Essentials/issues/1257#issuecomment-623029612