위치 업데이트를 얻고 액세스하려면 LocationManager
개체를 사용해야합니다. 빠른 업데이트를 위해 마지막으로 알려진 위치를 쿼리 할 수 있습니다.
중요한 점은 위치 관리자에게 청취를 요청한 후 거기에서 언제든지 빠른 업데이트를 요청할 수 있습니다. 나는 내 ApplicationContext
객체 (내가 로컬로 appModel
라고 부름)에 업데이트 된 위치 정보를 저장하는데, 이것은 객체 수명 기간 동안 지속된다.
나는이 같은 LocationManager
를 사용
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
startListening();
시작을 듣는 모습을 다음과 같이 :
public void startListening() {
if (gpsLocationListener == null) {
// make new listeners
gpsLocationListener = new CustomLocationListener(LocationManager.GPS_PROVIDER);
// request very rapid updates initially. after first update, we'll put them back down to a much lower frequency
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 200, gpsLocationListener);
}
//get a quick update
Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//this is the applicationContext object which persists for the life of the applcation
if (networkLocation != null) {
appModel.setLocation(networkLocation);
}
}
당신의 위치 수신기는 다음과 같이 수 :
private class CustomLocationListener implements LocationListener {
private String provider = "";
private boolean locationIsEnabled = true;
private boolean locationStatusKnown = true;
public CustomLocationListener(String provider) {
this.provider = provider;
}
@Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
handleLocationChanged(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
startListening();
}
public void onProviderDisabled(String provider) {
}
}
private void handleLocationChanged(Location location) {
if (location == null) {
return;
}
//get this algorithm from: http://developer.android.com/guide/topics/location/obtaining-user-location.html
if (isBetterLocation(location, appModel.getLocation())) {
appModel.setLocation(location);
stopListening();
}
}
행운을 빕니다!