Search code examples
androidonactivityresult

Refreshing activity after user changed location settings


User flow: Clicks a button, is redirected to MapActivity where a google maps is shown. A location is given, there is a button to make a route using current location to the given location. When location services is turned off the user is prompted to turn it on.

private void goToLocationSettings(){
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS );
    startActivityForResult(intent, 1);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == 1) {
        switch (requestCode) {
            case 1: Log.e("test", "onActivityResult");
                break;
        }
    }
}

When the user returns the function should be able to complete. But the program again to turn the settings on. The log is never shown.

If I wait a bit after turning on location services on my device I do not get the question to turn it on, but the log message is still not shown.

I have no idea what I am doing wrong.


Solution

  • You are checking for the wrong resultCode, to avoid confusion use constants Activity#RESULT_OK and Activity#RESULT_CANCELED. If you check the docs you can see that RESULT_OK has an int value of -1.

    In the case of starting Location Settings Activity for result, the resultCode will always be 0 because the user exits the Settings Activity with a back button, so to the system it looks like he canceled the request.

    static final int LOCATION_SETTINGS_REQUEST = 1;
    
     protected void onActivityResult(int requestCode, int resultCode,
             Intent data) {
         if (requestCode == LOCATION_SETTINGS_REQUEST) {
             // user is back from location settings - check if location services are now enabled
             checkGPS();
         }
     }