2011-02-03 93 views

回答

3

您可以使用下面的代碼來確定位置服務的狀態:

var watcher = new GeoCoordinateWatcher(); 
if (GeoPositionStatus.Disabled == watcher.Status) 
{ 
    // Watcher is disabled. 
}

更爲現實的,你要多注意改變的狀態(只是因爲服務不禁用並不意味着你有位置數據),所以你應該看看MSDN Documentation與位置服務工作。

還有一個很好的帖子filtering and emulating location data using the Reactive extensions,這是完美的預裝置測試,但爲了節省你的時間在Widnows Phone團隊發佈了Windows Phone GPS Emulator

+0

此代碼不起作用。始終顯示「無數據」! – user598328 2011-02-03 14:01:58

+0

您可能首先需要在觀察者上實際調用`Start()`並觀察狀態變化(這就是爲什麼我給了您鏈接以供進一步閱讀的原因)。如果您正在模擬器上運行,您幾乎肯定會一直獲得`NoData`狀態,這是使用包裝位置服務的Windows Phone GPS模擬器的另一個重要原因。 – 2011-02-03 14:23:52

3

即使已啓動GeoCoordinateWatcher,如果傳感器被禁用,您將獲得NoData。你應該嘗試使用的卻是TryStart:

GeoCoordinateWatcher g = new GeoCoordinateWatcher(); 
MessageBox.Show(g.TryStart(false,TimeSpan.FromSeconds(30)).ToString()); 

如果返回False,這意味着該傳感器被禁用。如果它返回True,則它被啓用。設置一個合適的超時時間(在上面的代碼片段中,我使用了30秒)並將此進程委派給輔助線程,以便它不會掛起UI。

+0

有趣的事實:在我的應用程序使用TryStart與位置禁用導致應用程序崩潰,所以是... – Esa 2012-10-15 11:33:42

2

您可以將StatusChanged事件添加到GeoCoordinateWatcher,並在觸發時在權限中測試GeoPositionPermission.Denied。

watcher = new GeoCoordinateWatcher(); 
watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged); 
watcher.Start(); 

void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e) 
{ 

    if (watcher.Permission == GeoPositionPermission.Denied) 
    { 
     // Location services were disabled 
    } 
} 

希望有所幫助。

4
  GeoCoordinateWatcher g = new GeoCoordinateWatcher(); 
      g.Start(); 
      if (g.Permission.Equals(GeoPositionPermission.Granted)) 
      { 
       //Your location services is enabled. Go ahead. 
       //Your codes goes here. 
      } 
      else if (g.Permission.Equals(GeoPositionPermission.Denied) || g.Permission.Equals(GeoPositionPermission.Unknown)) 
      {      
       MessageBox.Show("Location services are disabled. To enable them, Goto Settings - Location - Enable Location Services.", "Location services", MessageBoxButton.OK); 
      } 
0

取得這個基於TeJ'sanswer

public override void OnNavigatedTo() 
    {    
     using (var watcher = new GeoCoordinateWatcher()) 
     { 
      try 
      { 
       watcher.Start(); 
      } 
      finally 
      { 
       IsAllowedInSystem = watcher.Permission.Equals(GeoPositionPermission.Granted); 
       watcher.Stop(); 
      } 
     } 
    } 

而且我的應用ToggleSwitch.IsEnabled被綁定到IsAllowedInSystem。 當我切換到位置服務,禁用它並返回到應用程序,我的ToggleSwitch被禁用(也是一個字符串「請啓用位置服務在系統設置」在可見)。當我切換到位置服務,啓用它並返回到我的應用程序,我的ToggleSwitch已啓用,用戶可以進行設置。