fracz fracz - 1 year ago 355
Android Question

LocationListener and memory leaks

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 {
private LocationManager locationManager;

protected void onCreate(Bundle savedInstanceState) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

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
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?

Answer Source

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 (

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download