My Android app has two location listeners, one for fine and one for coarse listening. I want to be able to detect when the user turns their location services off and on.
Whenever I turn my phones GPS or network location services OFF the onProviderDisabled method is called as expected. When I turn GPS or network services ON the onProviderEnabled is never called!
I have put the code for one of the listeners below....
Update...
I have discovered that the problem is related to unregistering the listeners in onPause. When I remove the code "locationManager.removeUpdates(myFineLocationListener);" the onProviderEnabled() method IS called.
Perhaps the act of disabling the (say) GPS automatically unregisters the listener? Perhaps I should unregister thje listener in onDestroy rather than onPause() ???
PS. Maybe it is relevant that I mention that my activity has a button that goes directly to the devices location settings page. It acts as a shortcut. I use this shortcut to disable/enable location services then use the Back button to return to my app. I will put the code for this button at the very end of this post.
Code:
(The createLocListeners() method is called from onCreate();)
void createLocListeners() {
//if null, create a new listener
//myFineLocationListener is a class variable
if (myFineLocationListener == null) {
//Listen for FINE location updates
myFineLocationListener = new LocationListener(){
@Override
public void onLocationChanged(Location location) {
//Do something
}
@Override
public void onProviderDisabled(String provider) {
//This gets called when I change location settings (eg GPS on or off) on the phone }
@Override
public void onProviderEnabled(String provider) {
//This DOES NOT get called when I change location settings (eg GPS on or off) on the phone
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}; //end on location listener
} //end if fine listener is null
} //end createLocListener() function
@Override
protected void onResume() {
super.onResume();
//REGISTER LOCATION LISTENERS
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LISTENING_INTERVAL, LISTENING_DISTANCE, myFineLocationListener);
}
catch (IllegalArgumentException e){
//Tried catching exceptions but there weren't any
}
catch (RuntimeException e) {
}
}// end onResume()
@Override
protected void onPause() {
super.onPause();
//UNREGISTER LOCATION LISTENERS
locationManager.removeUpdates(myFineLocationListener);
} //end onPause
Similar problem: Location service onProviderEnabled never called
Code for button that opens the location Settings page...
//JUMP TO LOCATION SERVICES SETTINGS
ibLoc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}); //end jump to location services button listener
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…