2015-05-14 21 views
2

到目前爲止,我一直在使用GoogleApiClient獲取當前位置,但我剛剛注意到,使用LocationListenerLocationManager配合使用它會更簡單,因爲它甚至可以檢測用戶打開或關閉GPS服務的時間。如何使用LocationManager獲取初始位置?

但是我在初始化LocationManager後獲取用戶的第一個位置時遇到問題。

LocationManager有4位聽衆,但他們沒有一個會給你第一個位置。它確實有一個onLocationChanged監聽器,但它只在您移動時激活。

這是我如何使用它:

// Init LocationManager (needed to track if GPS is turned on or not 
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); 
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 


end of oncreate...... 


/* 
LocationListener (Listening if GPS service is turned on/off) 
*/ 

@Override 
public void onProviderEnabled(String provider) { 
} 

@Override 
public void onLocationChanged(Location location) { 
} 

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

@Override 
public void onProviderDisabled(String provider) { 
} 

回答

2

使用下面的方法來獲取Location對象:

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     Log.v(TAG, "isGPSEnabled =" + isGPSEnabled); 

     // getting network status 
     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     Log.v(TAG, "isNetworkEnabled =" + isNetworkEnabled); 

     this.canGetLocation = true; 
     if (isNetworkEnabled) { 
      locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
      Log.d(TAG, "Network"); 
      if (locationManager != null) { 
       location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
       if (location != null) { 
        latitude = location.getLatitude(); 
        longitude = location.getLongitude(); 
       } 
      } 
     } 
     // if GPS Enabled get lat/long using GPS Services 
     if (isGPSEnabled && location == null) { 
      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
      Log.d(TAG, "GPS Enabled"); 
      if (locationManager != null) { 
       location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
       if (location != null) { 
        latitude = location.getLatitude(); 
        longitude = location.getLongitude(); 
       } 
      } 
     } 
    } catch (Exception e) { 
     Log.e(TAG, "Location Not Found"); 
    } 
    return location; 
} 

欲瞭解更多有關該方法getLastKnownLocation,請refer to the docs

+2

不,永遠不要使用此代碼。它有很多bug,包括它並不總是使用GPS,可能會返回過時的數據或null,並且它並不總是擁有一個位置,即使它說明了它。請參閱http://gabesechansoftware.com/location-tracking/瞭解詳細信息 –

相關問題