2013-04-16 11 views
1

一如既往地獲得新位置?我在onCreate使用這個代碼在這裏Android始終在開放時獲得新位置

 locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE); 
     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
       if (isGPSEnabled) { 
         if (location == null) { 
          provider = LocationManager.GPS_PROVIDER; 
          locationManager.requestLocationUpdates(provider, 500, 0, this); 
          if (locationManager != null) { 
           location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);              
           if (location != null) { 
            latLng = new LatLng(location.getLatitude(), location.getLongitude());         
            if (location != null) {                            
             ParseQueryMap(); 
            } 
           } 
          } 
         } 
        }        
       if (isNetworkEnabled){ 
         if (location == null) { 
         provider = LocationManager.NETWORK_PROVIDER; 
         locationManager.requestLocationUpdates(provider, 500, 0, this); 
         if (locationManager != null) {     
          location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);  
          if (location != null) { 
           latLng = new LatLng(location.getLatitude(), location.getLongitude());        
           if (location != null) { 
            ParseQueryMap();        
           } 
          } 
         } 
         } 
        } 
       } 

如果該位置不可用,當我運行應用程序使以前已知位置(getLastKnownLocation())。我不喜歡這個解決方案。我需要立即或在一段時間後(約5秒)向我展示我的確切位置。啓動時的確切位置我需要顯示基地的最近點。可能嗎?感謝您的幫助

+0

如果用戶禁用GPS,您將無法獲得確切位置。如果用戶啓用了GPS,那麼如果您選擇提供者,那麼您將收到「來自網絡」的位置,這將不會太遠。 Android本身(如果配置爲這樣)會定期刷新「最後一次知道的位置」,所以它不會那麼差。對於一個確切的位置,你需要獲得一個GPS修復,這可能需要(取決於設備和連接)幾秒鐘(甚至超過五個)。其他可能性:在後臺運行服務以每x秒/分鐘刷新一次位置。消耗很多電池。 – damian

+0

@ damian - 在這種情況下我會推薦做什麼?我希望用戶打開一個應用程序,查看最近的點並去找她。 –

回答

1

嘗試被動定位提供商。通過使用它,您可以接收位置更新以及其他已經請求它們的應用程序。

請參閱this blog entry其中詳細描述瞭如何儘可能快地修復位置。您可以在android-protips-location項目中找到示例代碼。

+0

感謝您的鏈接,但也有最新的位置在「新鮮意味着永不需要等待」。或者我不明白的東西? –

+0

確切地說,不幸的是,沒有辦法立刻獲得當前位置。這是GPS/Wi-Fi定位的技術限制,而不是Android。我們必須等待GPS定位或收集設備周圍的Wi-Fi信號並詢問位置服務器。所以,我想我們所能做的就是實現上面鏈接中描述的代碼。 – tnj

+0

@ Chernoff20在[最新的Google I/O會話]中引入的Google Play服務API中,嘗試[Fused Location Provider](https://developer.android.com/google/play-services/location.html)(https: //developers.google.com/events/io/sessions/325337477)。總之,[LocationClient#getLastLocation()](https://developer.android.com/reference/com/google/android/gms/location/LocationClient.html#getLastLocation())應該對你很好。 – tnj