Please consider this chunk of code:
public class Presence implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener
{
:
:
boolean pref_auto_mode;
:
:
private Presence(Context context)
{
this.context = context;
getAppSettings();
gApiClient = new GoogleApiClient.Builder(context, this, this)
.addApi(LocationServices.API)
.build();
createLocationRequest();
if (!gApiClient.isConnecting() && !gApiClient.isConnected())
{
gApiClient.connect();
}
} // of constructor
@Override
public void onConnected(Bundle connectionHint)
{
Log.e(LOG_TAG, "In onConnected(), gApiClient.isConnected(): " + gApiClient.isConnected());
createLocationRequest();
getLocation();
getSubLocality();
if (pref_auto_mode)
startLocationUpdates();
} // of onConnected()
:
:
private void getAppSettings()
{
// Get the user's preferences
APP_USER_SETTINGS = PreferenceManager.getDefaultSharedPreferences(context);
:
:
pref_auto_mode = APP_USER_SETTINGS.getBoolean(Contract.PREF_AUTO_MODE, false);
:
} // of getAppSettings()
} // of class Presence
This is working as expected.
In the same Presence
class above, I am trying to stop the location updates when the user switches a certain setting off, with the following method:
public void stopLocationUpdates()
{
if (gApiClient.isConnected())
{
LocationServices.FusedLocationApi.removeLocationUpdates(gApiClient, pendingIntent);
LocationServices.FusedLocationApi.removeLocationUpdates(gApiClient, this);
Log.e(LOG_TAG, "Location tracker stopped successfully.");
requestingLocationUpdates = false;
}
}
I do see the Toast
. There are no location updates and everything is silent as expected. But after a couple of hours of moving around with the device, all of a sudden, I start getting location updates again, as in, all the code in the onHandleIntent()
of the IntentService
get faithfully executed when there's a location change.
To set the Auto mode, the user has to launch the app, so the Presence
class will certainly be instantiated (Singleton) and whatever is set in the app is reflected onto its pref_auto_mode
flag, if I am not wrong. Yet, I suspect this flag.
Kindly let me know what else I need to do to bring the location updates to a grinding halt instantly and keep it that way till the user switches the setting ON? Am I doing something wrong or missing something?
Many thanks in advance!
Thanks to all who reviewed the code and provided valuable pointers.
I had to make another boolean
field variable stopLocationTrackerRequired
and set it in the onSharedPreferenceChanged()
override. Only if this flag is set, the Presence
class's stopLocationUpdates()
is invoked, and for sure turns off the location updates.
For completeness,:
- Kindly let me know what else I need to do to bring the location updates to a grinding halt instantly and keep it that way till the user switches the setting ON?
- Am I doing something wrong or missing something?
stopLocationUpdates()
is doing everything required to achieve the functionality.