Recipe 9.4 Turning GPS On/Off

Android Versions
Level 1 and above
Permissions
ACCESS_FINE_LOCATION
ACCESS_COARSE_LOCATION
Source Code to Download from Wrox.com
ToggleGPS.zip

If you have a location-based service (LBS) application that relies on the Global Positioning System (GPS) or network triangulation, you need to ensure that the relevant settings in the Location Services page in the Settings application are enabled. This recipe demonstrates how to detect whether the relevant settings are turned on; and if not, how to direct the page to the user to enable the settings.

Solution

To determine if location services are enabled on the device, you first obtain an instance of the LocationManager class. Using this instance, you can then check whether the GPS or network provider is enabled by using the isProviderEnabled() method, as demonstrated in the following code snippet:

package net.learn2develop.togglegps;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LocationManager lm = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
        //---check if GPS_PROVIDER is enabled---
 boolean gpsStatus = lm.isProviderEnabled(LocationManager.GPS_PROVIDER); ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.