Home | History | Annotate | Download | only in location
      1 page.title=Using the Location Manager
      2 parent.title=Making Your App Location Aware
      3 parent.link=index.html
      4 
      5 trainingnavtop=true
      6 next.title=Obtaining the Current Location
      7 next.link=currentlocation.html
      8 
      9 @jd:body
     10 
     11 
     12 <!-- This is the training bar -->
     13 <div id="tb-wrapper">
     14 <div id="tb">
     15 
     16 <h2>This lesson teaches you to</h2>
     17 <ol>
     18   <li><a href="locationmanager.html#TaskDeclarePermissions">Declare Proper Permissions in Android Manifest</a></li>
     19   <li><a href="locationmanager.html#TaskGetLocationManagerRef">Get a Reference to LocationManager</a></li>
     20   <li><a href="locationmanager.html#TaskPickLocationProvider">Pick a Location Provider</a></li>
     21   <li><a href="locationmanager.html#TaskVerifyProvider">Verify the Location Provider is Enabled</a></li>
     22 </ol>
     23 
     24 <h2>You should also read</h2>
     25 
     26 <ul>
     27   <li><a href="{@docRoot}guide/topics/location/index.html">Location and Maps</a></li>
     28 </ul>
     29 
     30 <h2>Try it out</h2>
     31 
     32 <div class="download-box">
     33 <a href="http://developer.android.com/shareables/training/LocationAware.zip" class="button">Download
     34   the sample app</a>
     35 <p class="filename">LocationAware.zip</p>
     36 </div>
     37 
     38 </div>
     39 </div>
     40 
     41 <p>Before your application can begin receiving location updates, it needs to perform some simple steps to set up access.  In this lesson, you'll learn what these steps entail.</p>
     42 
     43 <h2 id="TaskDeclarePermissions">Declare Proper Permissions in Android Manifest</h2>
     44 
     45 <p>The first step of setting up location update access is to declare proper permissions in the manifest.  If permissions are missing, the application will get a {@link java.lang.SecurityException} at runtime.</p>
     46 
     47 <p>Depending on the {@link android.location.LocationManager} methods used, either {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} or {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission is needed.  For example, you need to declare the {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} permission if your application uses a network-based location provider only.  The more accurate GPS requires the {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission.
     48 Note that declaring the {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission implies {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} already.</p>
     49 
     50 <p>Also, if a network-based location provider is used in the application, you'll need to declare the internet permission as well.</p>
     51 
     52 <pre>
     53 &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt;
     54 &lt;uses-permission android:name="android.permission.INTERNET" /&gt;
     55 </pre>
     56 
     57 <h2 id="TaskGetLocationManagerRef">Get a Reference to LocationManager</h2>
     58 
     59 <p>{@link android.location.LocationManager} is the main class through which your application can access location services on Android.  Similar to other system services, a reference can be obtained from calling the {@link android.content.Context#getSystemService(java.lang.String) getSystemService()} method.  If your application intends to receive location updates in the foreground (within an {@link android.app.Activity}), you should usually perform this step in the {@link android.app.Activity#onCreate(android.os.Bundle) onCreate()} method.</p>
     60 
     61 <pre>
     62 LocationManager locationManager =
     63         (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
     64 </pre>
     65 
     66 <h2 id="TaskPickLocationProvider">Pick a Location Provider</h2>
     67 
     68 <p>While not required, most modern Android-powered devices can receive location updates through multiple underlying technologies, which are abstracted to an application as {@link android.location.LocationProvider} objects.  Location providers may have different performance characteristics in terms of time-to-fix, accuracy, monetary cost, power consumption, and so on.  Generally, a location provider with a greater accuracy, like the GPS, requires a longer fix time than a less accurate one, such as a network-based location provider.</p>
     69 
     70 <p>Depending on your application's use case, you have to choose a specific location provider, or multiple providers, based on similar tradeoffs.  For example, a points of interest check-in application would require higher location accuracy than say, a retail store locator where a city level location fix would suffice.  The snippet below asks for a provider backed by the GPS.</p>
     71 
     72 <pre>
     73 LocationProvider provider =
     74         locationManager.getProvider(LocationManager.GPS_PROVIDER);
     75 </pre>
     76 
     77 <p>Alternatively, you can provide some input criteria such as accuracy, power requirement, monetary cost, and so on, and let Android decide a closest match location provider.  The snippet below asks for a location provider with fine accuracy and no monetary cost.  Note that the criteria may not resolve to any providers, in which case a null will be returned.  Your application should be prepared to gracefully handle the situation.</p>
     78 
     79 <pre>
     80 // Retrieve a list of location providers that have fine accuracy, no monetary cost, etc
     81 Criteria criteria = new Criteria();
     82 criteria.setAccuracy(Criteria.ACCURACY_FINE);
     83 criteria.setCostAllowed(false);
     84 ...
     85 String providerName = locManager.getBestProvider(criteria, true);
     86 
     87 // If no suitable provider is found, null is returned.
     88 if (providerName != null) {
     89    ...
     90 }
     91 </pre>
     92 
     93 <h2 id="TaskVerifyProvider">Verify the Location Provider is Enabled</h2>
     94 
     95 <p>Some location providers such as the GPS can be disabled in Settings.  It is good practice to check whether the desired location provider is currently enabled by calling the {@link android.location.LocationManager#isProviderEnabled(java.lang.String) isProviderEnabled()} method.  If the location provider is disabled, you can offer the user an opportunity to enable it in Settings by firing an {@link android.content.Intent} with the {@link android.provider.Settings#ACTION_LOCATION_SOURCE_SETTINGS} action.</p>
     96 
     97 <pre>
     98 &#64;Override
     99 protected void onStart() {
    100     super.onStart();
    101 
    102     // This verification should be done during onStart() because the system calls
    103     // this method when the user returns to the activity, which ensures the desired
    104     // location provider is enabled each time the activity resumes from the stopped state.
    105     LocationManager locationManager =
    106             (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    107     final boolean gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    108 
    109     if (!gpsEnabled) {
    110         // Build an alert dialog here that requests that the user enable
    111         // the location services, then when the user clicks the "OK" button,
    112         // call enableLocationSettings()
    113     }
    114 }
    115 
    116 private void enableLocationSettings() {
    117     Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    118     startActivity(settingsIntent);
    119 }
    120 </pre>
    121