I'm trying to convert an Activity which uses LocationListener to a Fragment, using LocationManager like this:
protected LocationManager locationManager;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
locationManager = (LocationManager) getActivity().getSystemService(
Context.LOCATION_SERVICE);
(...)
}
I'm having some problems with these methods (can't get rid of the errors):
if (location != null) {
// location known:
onLocationChanged(location); // Error here
}
boolean startLocationUpdates() {
boolean result = false;
for (final String provider : locationManager.getProviders(true)) {
locationManager.requestLocationUpdates(provider, 2 * 1000, 0.0f,
this); // Error here
result = true;
}
return result;
}
@Override
public void onPause() {
super.onPause();
locationManager.removeUpdates(this); // Error here
savePrefs();
}
How can I use these methods inside a fragment?
You're mixing up the relationship between the
LocationManagerand theLocationListenerthat actually receives the updates. For example, onLocationChanged, where you indicate an error, is really a callback that theLocationListeneryou assign to thatLocationManageruses to pass a new location object to your activity/fragment. It's not something you call yourself.The way your
LocationListenerandLocationManagerwould interact is something like this. You'd have an instance of both within your fragment.onActivityCreatedyou would initilize both theLocationManagerandLocationListenerwith theLocationListenerimplementing all the required callbacks below.Your
LocationListnerwould then call onLocationChanged each time the locatino change met whatever critera you assigned at creation. Check the android docs for LocationManager and LocationListener for more details.