Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 910
fracz Avatar asked Dec 20 '22 19:12

fracz


1 Answers

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)

like image 156
Dimmerg Avatar answered Jan 05 '23 00:01

Dimmerg