2016-08-19 38 views
0

我正在使用xamarin表單。我需要檢查位置服務是否啓用了Android。我寫了下面的代碼:IsProviderEnabled總是返回true定位服務啓用或禁用

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

但我總是得到真正的價值無論是位置服務啓用或不。我如何才能獲得正確的價值?

+0

你使用模擬器還是真實設備? –

+0

我在模擬器和真實設備上都進行了測試。但得到相同的結果是true – anand

回答

0

如果您在Xamarin.Forms中工作,爲什麼不使用nuget包Xam.Plugin.Geolocator?我正在使用它,並將我的位置代碼放入PCL中,因此它是跨平臺的,不會重複。如果你真的只需要在Android中的位置,你可以把這個片段放在你的android項目中。

(I通常包裹插件所以可以最大限度地減少它們的影響,因此包裝類和在該示例中的界面)

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。 由於它是開源的,你可以查看implementation on Android

+0

但我需要知道位置服務是否啓用。在這裏,您正在獲取設備的位置,而不是關於位置服務是否已啓用。 – anand

+0

@anand它是一個開源項目,所以你可以看到實現。它有你正在尋找的方法,如果你只是去檢查它。我用確切的鏈接更新了這篇文章。 – valdetero

+0

感謝您的更新,我嘗試了它,但我仍然在兩種情況下都變得真實無論是否啓用位置服務。 – anand

0

如果使用Plugin.Geolocator.CrossGeolocator,認識到這一點:

IsGeolocationEnabledIsGeolocationAvailable只返回後位置的應用程序的權限被允許的正確的信息!!!!!

如果你想知道,如果位置服務在移動啓用之前,允許定位應用程序權限,你必須這樣做:

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