In my app, I am using two location managers for two different activities. First location manager is created when the first activity is created. And then from the first activity I am creating a second activity which is creating a second location manager. In the second activity, I am trying to stop location manager updates using the following code when the back button is pressed:
@Override
public void onBackPressed() {
lm.removeUpdates(ll);
ll = null;
lm = null;
finish();
}
ll and lm are declared globally in both first and second activity seperatly.
ll and lm are initialized in onCreate of second activity using following code:
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, ll);
The problem is that if I don’t go to the second activity and stop the first activity’s location updates, then the GPS sign in my Android goes away. But if I go to the second activity, come back to the first activity using the back button and then stop the first acivity’s location updates, then the GPS location sign is still there. I am stopping updates in the first activity using same line of codes:
lm.removeUpdates(ll);
ll = null;
lm = null;
ll and lm in first activity are initialized when start button is pressed:
public void startClick (View target){
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
ll = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, ll);
}
Is there any kind of mistake in the code or is there any logical error? Thanks in advance.
You can have a single instance of the
LocationManagerand store it in yourApplication Context. To do so you need to create a class that extendsApplication. Here’s an example:Do not forget to add a reference to
MyApplicationin theandroid:nameattribute in theAndroidManifest.xmlfile. Something like this:To access your locationManager instance you call this piece of code:
To instantiate the locationManager instance inside your Activity you use this:
}
Hope that helps:)