According to the sample app that finds the user location it is a good idea to listen for location changes in the activity:
class MyActivity extends Activity implements LocationListener {
@Inject
private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
// do something with location
}
// ...
}
However, I'm not sure about that. When there is a configuration change, my activity gets destroyed and recreated, registering itself as listener next time. The reference to the old Activity is held in the LocationManager, isn't it?
If I extract the LocationListener
to separate object, still I have the problem of how to notify the current activity about new location (not necessarily the same as the requesting activity).
Is there any common pattern to solve this?
In this example you have also another problem: your GPS listener will work always and will drain battery.
The better practice is:
1) register LocationListener into Activity's onStart()
2) remove LocationListener into Activity's onStop()
This will fix both problems.
If you need that your app track user position in background (for example, GPS tracker) use Service
(http://developer.android.com/reference/android/app/Service.html)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With