2012-08-23 173 views
0

我試圖根據網絡提供程序獲取用戶位置,但該事件從未發生,並且UpdateLocation()方法從未被調用。 代碼如下:獲取用戶位置Android

public void UpdateLocation(Location location) 
{ 
    GeoPoint geoPoint = new GeoPoint((int)(location.getLatitude() * 1E6),(int)(location.getLongitude() * 1E6)); 
    MapController controller = mapView.getController(); 
    controller.setCenter(geoPoint); 
} 
public void GetLocation() 
{ 
    // Acquire a reference to the system Location Manager 
    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

    // Define a listener that responds to location updates 
    LocationListener locationListener = new LocationListener() { 
     public void onLocationChanged(Location location) { 
      // Called when a new location is found by the network location provider. 
      UpdateLocation(location); 
     } 

     public void onStatusChanged(String provider, int status, Bundle extras) {} 

     public void onProviderEnabled(String provider) {} 

     public void onProviderDisabled(String provider) {} 
     }; 

    // Register the listener with the Location Manager to receive location updates 
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); 
} 

可能是什麼問題?我在這裏做錯了什麼?

+0

你在一個設備或模擬器上使用它? – Sam

+0

您是否在清單中添加了正確的權限?像INTERNET和ACCESS_COARSE_LOCATION一樣? –

+0

@Sam Emulatorrr – idish

回答

1

如果我正確記得,NETWORK_PROVIDER使用wifi信號找出位置。

夫婦的事情來驗證:

  • 是無線網絡上?
  • 設備是否註冊了wifi信號?超過一個? (一個可能不夠)
  • 是否在設置中的「位置服務」下選中「使用無線網絡」?
+0

我在模擬器上運行此代碼,而不是在設備上,我正在使用筆記本電腦並啓用了Wifi。 – idish

+0

它不會在模擬器上工作。有辦法欺騙GPS修正,但我不認爲我已經看到任何將不幸做NETWORK_PROVIDER的事情。也許有人知道這個模擬器。 – Nick

+0

你可以做的一件事是切換到傾聽GPS並模擬它。它應該至少可以讓你測試代碼的其他部分,如「UpdateLocation」。看到這裏:http://stackoverflow.com/questions/2279647/how-to-emulate-gps-location-in-the-android-emulator – Nick

0

你應該檢查你的位置提供商請求該位置之前啓用:

locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

給這個教程看看。它包括sample code

+0

請注意,您應該在此處發佈答案的有用觀點,或將您的帖子風險刪除爲[「未答覆」](http://meta.stackexchange.com/q/8259)。如果您願意,您可能仍然包含鏈接,但僅作爲「參考」。答案應該獨立,不需要鏈接。 –