0

我正在以 xamarin 形式工作。我需要检查是否为 android 启用了位置服务。我写了以下代码:

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

但无论是否启用位置服务,我总是能获得真正的价值。我怎样才能得到正确的值?

4

2 回答 2

1

如果您使用的是 Plugin.Geolocator.CrossGeolocator,请注意这一点:

IsGeolocationEnabledIsGeolocationAvailable仅在允许位置的应用程序权限后返回正确的信息!!!!!!

如果您想知道在允许位置应用程序权限之前是否在移动设备上启用了位置服务,您必须这样做:

安卓

  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;
    }
于 2017-08-23T11:54:10.190 回答
-1

如果您在 Xamarin.Forms 中工作,为什么不使用 nuget 包Xam.Plugin.Geolocator?我正在使用它,并将我的位置代码放在我的 PCL 中,因此它是跨平台的并且不会重复。如果你真的只需要 Android 中的位置,你可以把这个片段直接放在你的 android 项目中。

(我通常包装插件,因此我可以最大限度地减少它们的影响,因此包装类和示例中的接口)

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;
        }
    }
}

如果需要,这可以全部压缩为一行:

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

编辑:该插件还具有确定地理位置状态的方法,例如IsGeolocationEnabledIsGeolocationAvailable。由于它是开源的,您可以在 Android 上查看实现

于 2016-08-19T20:33:36.567 回答