Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android locationManager continues to call onLocationChanged after removeUpdates

I've an app that gets a location fix. The app is to be rolled out to phones from Gingerbread up. Once the app gets a location fix a toast message is displayed to the user. The problem is when the user moves to the next activity the toast message appears maybe ten more times.

I think i've implemented the lifecycles correctly eg

1) get a location manager in onCreate() 2) create and pass a location listener to the manager in onResume() 3) remove updates in onStop()

I understand i can bypass this problem in Android > 4.x by calling

mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlocListener, null);

but i have to accommodate Gingerbread so calling a single request is not in api 2.3.x. It works fine on Android 4 but on gingerbread the onLocationChanged method keeps executing another 10 times.

How can i force the onLocationChanged method to run only once on gingerbread?

thanks.

[edit] I've noticed that when i move to the next activity the onlocationchanged method keeps executing but if i move to a further activity then the location requests are successfully removed

@Override
protected void onStop() {
    mlocManager.removeUpdates(mlocListener); 
    mlocListener = null;
    super.onStop();
}

@Override
protected void onResume() {
    mlocListener = new MyLocationListener();
    if(isCompOptionsReceived == true){
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER, mlocListener, null);
        }else{
            mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);   
        }
    }        
    super.onResume();
}

private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        //toast message
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status,                        Bundle extras) {
    }

}//end of MyLocationListener

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    nfcscannerapplication = (NfcScannerApplication) getApplication();
    sIs = savedInstanceState;
    setContentView(R.layout.entryscreen);
    mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
like image 376
turtleboy Avatar asked Dec 04 '12 16:12

turtleboy


1 Answers

The following code should be executed on the onPause method, not in the onStop

mlocManager.removeUpdates(mlocListener); 
mlocListener = null;

That will fix it for all the android versions.

like image 92
Robert Estivill Avatar answered Nov 18 '22 11:11

Robert Estivill