简体   繁体   中英

IsProviderEnabled always return true either Location service is enabled or disabled

I am working in xamarin forms. I need to check the location service is enabled or not for android. I wrote the following code :

   LocationManager locMgr = GetSystemService(LocationService) as LocationManager;
   string Provider = LocationManager.GpsProvider;
   var islocationEnabled = locMgr.IsProviderEnabled(Provider);

But I am always getting true value either location service is enabled or not. How I can get the correct value?

If you are using Plugin.Geolocator.CrossGeolocator, be aware of this:

IsGeolocationEnabled and IsGeolocationAvailable returns the correct info only AFTER the App Permissions for Locations was allowed!!!!!

If you want to know if the locations services are enabled on the mobile BEFORE you allow the Location App Permission, you have to do like this:

Android

  public bool IsLocationGpsEnabled()
    {
        var _locationManager = (LocationManager)Forms.Context.GetSystemService(Context.LocationService);
        if (_locationManager.IsProviderEnabled("gps"))
        {
            return true;
        }

        return false;
    }

iOS

 public bool IsLocationGpsEnabled()
    {
        return CLLocationManager.LocationServicesEnabled;
    }

If you are working in Xamarin.Forms, why not use the nuget package Xam.Plugin.Geolocator ? I'm using it and I put my location code in my PCL so it's cross-platform and not repeated. You could take this snippet and put it straight in your android project if you really only needed location in Android.

(I usually wrap plugins so I can minimize their impact, hence the wrapper class and the interface in the example)

public class LocationService : ILocationService
{
    readonly ILogger _logger;
    public LocationService(ILogger logger)
    {
        _logger = logger;
    }

    public async Task<IPosition> GetPosition()
    {
        var locator = Plugin.Geolocator.CrossGeolocator.Current;

        //1609 meters in a mile. Half a mile accuracy should be good 
        //since we are rounding to whole numbers
        locator.DesiredAccuracy = 800;

        try
        {
            var position = await locator.GetPositionAsync(5000);

            return position.ToPosition();
        }
        catch (Exception ex)
        {
            _logger.Log(ex);
            return null;
        }
    }
}

This could all be condensed to one line if needed:

return await Plugin.Geolocator.CrossGeolocator.Current.GetPositionAsync();

EDIT: The plugin also has methods for determining the status of geolocation like IsGeolocationEnabled and IsGeolocationAvailable . Since it is open-source, you can view the implementation on Android .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM