14

I have two files MainActivity.java and HomeFragment.java in the MainActivity calls a function from HomeFragment that asks the user to turn on the location services on their phone. The problem is even when the user has the location feature already turned on the function is called anyway. Is there a way I can make it so only when the location feature is off that the function from the HomeFragment is launched.

HomeFragment.java

public static void displayPromptForEnablingGPS(
        final Activity activity)
{
    final AlertDialog.Builder builder =
            new AlertDialog.Builder(activity);
    final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
    final String message = "Enable either GPS or any other location"
            + " service to find current location.  Click OK to go to"
            + " location services settings to let you do so.";


    builder.setMessage(message)
            .setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int id) {
                            activity.startActivity(new Intent(action));
                            d.dismiss();
                        }
                    });

    builder.create().show();
}

MainActivity.java

public void showMainView() {
    HomeFragment.displayPromptForEnablingGPS(this);
}

Thank you :)

Bruno Albuquerque
  • 161
  • 1
  • 1
  • 8
  • 3
    First result from Google: http://stackoverflow.com/questions/843675/how-do-i-find-out-if-the-gps-of-an-android-device-is-enabled – BooleanCheese Dec 09 '15 at 17:20

1 Answers1

29

You could use something like this:

final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
    // Call your Alert message
}

That should do the trick.

To check if Location Services are enabled, you can use code similar to this:

String locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (locationProviders == null || locationProviders.equals("")) {
...
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}

Source: Marcus' Post found here

Community
  • 1
  • 1
liquidsystem
  • 636
  • 5
  • 14
  • liquidsystem thank you this work, but i was wondering if instead of GPS_PROVIDER if it could verify if "Access to my location" is active. Im asking because the user can have the "Use wireless networks" on and this also works. – Bruno Albuquerque Dec 09 '15 at 17:47
  • This should provide you with your question: https://scotthelme.co.uk/android-location-services/ – liquidsystem Dec 09 '15 at 17:49
  • thank you for the response but i ended up using an "or" statement: if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) || !manager.isProviderEnabled( LocationManager.NETWORK_PROVIDER ) ) – Bruno Albuquerque Dec 09 '15 at 19:54