我需要在我的應用程序中更新位置。我試圖通過在我的所有活動中添加下面顯示的代碼來完成此操作。我的問題是,我不能確定用戶會保持足夠長的時間來完成更新。我怎麼能有一些應用程序明智的聽衆每次給定的時間獲得更新的位置(比如30分鐘)?在我的應用程序中獲取更新位置
private LocationManager mLocationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// My activity stuff
}
private Location getBestLocation(LocationManager locationManager) {
Location location_gps = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location_network = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// If both are available, get the most recent
if(location_gps!=null && location_network !=null) {
return (location_gps.getTime() > location_network.getTime())?location_gps:location_network;
}
else if(location_gps==null && location_network ==null){
return null;
}
else
return (location_gps==null)?location_network:location_gps;
}
@Override
protected void onResume() {
super.onResume();
// Request location updates at startup
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DIST, this);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_MIN_TIME, LOCATION_UPDATE_MIN_DIST, this);
getBestLocation(mLocationManager)
}
@Override
protected void onPause() {
super.onPause();
// Remove the locationlistener updates when Activity is paused
mLocationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location) {
GlobalVars.lat = (Double) (location.getLatitude());
GlobalVars.lng = (Double) (location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// Nothing here
}
@Override
public void onProviderEnabled(String provider) {
Location location = getBestLocation(mLocationManager);
// Initialize the location fields
if (location != null) {
GlobalVars.lat = (Double) (location.getLatitude());
GlobalVars.lng = (Double) (location.getLongitude());
}
}
@Override
public void onProviderDisabled(String provider) {
}