Tag: Android

Programming Stuff

Programmatically Enable Android GPS and Location Services

I remember the “good ol’ days” of location-based programming where there was a simple API call that allowed an application to enable or disable a mobile device’s GPS service. Today, user privacy and security concerns make that sort’a thing no longer possible.

In today’s world, a phone’s user generally has ultimate control of what features are and are not enabled on their phone. Although I agree this behavior is best for users, it definitely creates headaches for developers.

The one thing we know we can’t do as developers, is display a message that simply says “Hey! Go turn on your GPS”. Seeing a message like that would cause most users to uninstall our app and look for an app that’s easier to use.

The good news is that as developers we can send the user directly to the location settings screen right from within our app with a simple Intent.

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);

The exact format of the screen the user sees will vary based on their Android version and device model, but the above code will always take them to the appropriate settings screen. On my Samsung device, the ACTION_LOCATION_SOURCE_SETTINGS screen looks like the following…

LocationSettings

In general what I’ll do is use the LocationManager class to check for the availability of the required location services. If the services aren’t enabled,  I’ll show an AlertDialog informing the user of what they need to do and then show the settings screen in the dialog’s click handler. Here’s that code…

// Get Location Manager and check for GPS & Network location services
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
      !lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
  // Build the alert dialog
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setTitle("Location Services Not Active");
  builder.setMessage("Please enable Location Services and GPS");
  builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
  public void onClick(DialogInterface dialogInterface, int i) {
    // Show location settings when the user acknowledges the alert dialog
    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    startActivity(intent);
    }
  });
  Dialog alertDialog = builder.create();
  alertDialog.setCanceledOnTouchOutside(false);
  alertDialog.show();
}

That little bit of code can go a long way to both ensuring that your app has access to the required location services and that the user has a positive experience.

This post is adapted from Jim’s Plurasight Course

AndroidLBS_436x155

For more information about Jim and his courses visit his Pluralsight Author Page