Reputation: 3092
I have a class "OldLocationService" (generally I'm using fused location from GoogleApiClient but I keep that class in case of old Google Play):
public class OldLocationService {
static Location loc;
private static final String TAG = MainActivity.class.getSimpleName();
protected LocationManager service;
private final LocationListener mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(final Location location) {
Log.d(TAG, "New location: " + location.toString());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
};
public void EnableGPS(String provider, Context ctx) {
service = (LocationManager) ctx.getSystemService(ctx.LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(provider);
if (enabled) {
service.requestLocationUpdates(provider, 10000, 0, mLocationListener, Looper.getMainLooper());
}
else
{
Log.d(TAG, "GPS is not enabled");
}
}
public void DisableGPS() {
try {
if (!(service==null)) {
service.removeUpdates(mLocationListener);
} else {
Log.d(TAG, "service is null");
}
} catch(Exception e) {
e.printStackTrace();
}
}
}
Somewhere in another class I'm calling:
OldLocationService OLS = new OldLocationService();
OLS.EnableGPS(LocationManager.NETWORK_PROVIDER, mContext);
And I'm getting locations correctly. However, when I'm trying to disable GPS:
OldLocationService ols = new OldLocationService();
ols.DisableGPS();
Then in logcat I get:
service is null
Why I can't remove GPS updates? How to do that?
Sorry for my English errors,
Defozo
Upvotes: 1
Views: 174
Reputation: 4192
First of all don't make 2 instances of your OldLocationService
class.. you must remove updates from the same instance from which you started them.. because each instance has its own copy of variables/fields, in your case protected LocationManager service;
OldLocationService ols = new OldLocationService(); // declare it globally
// in middle of some code
OLS.EnableGPS(LocationManager.NETWORK_PROVIDER, mContext);
// more code here
If you're removing Location updates from a Service
then you must put the code in it's onDestroy()
method from the same instance:
public void onDestroy(){
ols.DisableGPS();
super.onDestroy();
}
Upvotes: 1