page.title=Obtaining the Current Location
parent.title=Making Your App Location Aware
parent.link=index.html

trainingnavtop=true
previous.title=Using the Location Manager
previous.link=locationmanager.html
next.title=Displaying the Location Address
next.link=geocoding.html


@jd:body


<!-- This is the training bar -->
<div id="tb-wrapper">
<div id="tb">

<h2>This lesson teaches you to</h2>
<ol>
  <li><a href="currentlocation.html#TaskSetupLocationListener">Set Up the Location Listener</a></li>
  <li><a href="currentlocation.html#TaskHandleLocationUpdates">Handle Multiple Sources of Location Updates</a></li>
  <li><a href="currentlocation.html#TaskGetLastKnownLocation">Use getLastKnownLocation() Wisely</a></li>
  <li><a href="currentlocation.html#TaskTerminateUpdates">Terminate Location Updates</a></li>
</ol>

<h2>You should also read</h2>

<ul>
  <li><a href="{@docRoot}guide/topics/location/index.html">Location and Maps</a></li>
</ul>

<h2>Try it out</h2>

<div class="download-box">
<a href="http://developer.android.com/shareables/training/LocationAware.zip" class="button">Download
  the sample app</a>
<p class="filename">LocationAware.zip</p>
</div>

</div>
</div>

<p>After setting up your application to work with {@link android.location.LocationManager}, you can begin to obtain location updates.</p>

<h2 id="TaskSetupLocationListener">Set Up the Location Listener</h2>

<p>The {@link android.location.LocationManager} class exposes a number of methods for applications to receive location updates.  In its simplest form, you register an event listener, identify the location manager from which you'd like to receive location updates, and specify the minimum time and distance intervals at which to receive location updates.  The {@link android.location.LocationListener#onLocationChanged(android.location.Location) onLocationChanged()} callback will be invoked with the frequency that correlates with time and distance intervals.</p>

<p>
In the sample code snippet below, the location listener is set up to receive notifications at least every 10 seconds and if the device moves by more than 10 meters.  The other callback methods notify the application any status change coming from the location provider.
</p>

<pre>
private final LocationListener listener = new LocationListener() {

    &#064;Override
    public void onLocationChanged(Location location) {
        // A new location update is received.  Do something useful with it.  In this case,
        // we're sending the update to a handler which then updates the UI with the new
        // location.
        Message.obtain(mHandler,
                UPDATE_LATLNG,
                location.getLatitude() + ", " +
                location.getLongitude()).sendToTarget();

            ...
        }
    ...
};

mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
        10000,          // 10-second interval.
        10,             // 10 meters.
        listener);
</pre>

<h2 id="TaskHandleLocationUpdates">Handle Multiple Sources of Location Updates</h2>

<p>Generally speaking, a location provider with greater accuracy (GPS) requires a longer fix time than one with lower accuracy (network-based).  If you want to display location data as quickly as possible and update it as more accurate data becomes available, a common practice is to register a location listener with both GPS and network providers.  In the {@link android.location.LocationListener#onLocationChanged(android.location.Location) onLocationChanged()} callback, you'll receive location updates from multiple location providers that may have different timestamps and varying levels of accuracy.  You'll need to incorporate logic to disambiguate the location providers and discard updates that are stale and less accurate.  The code snippet below demonstrates a sample implementation of this logic.</p>

<pre>
private static final int TWO_MINUTES = 1000 * 60 * 2;

/** Determines whether one Location reading is better than the current Location fix
  * @param location  The new Location that you want to evaluate
  * @param currentBestLocation  The current Location fix, to which you want to compare the new one
  */
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;
    }

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta &gt; TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta &lt; -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
    // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;
    }

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta &gt; 0;
    boolean isMoreAccurate = accuracyDelta &lt; 0;
    boolean isSignificantlyLessAccurate = accuracyDelta &gt; 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),
            currentBestLocation.getProvider());

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer &amp;&amp; !isLessAccurate) {
        return true;
    } else if (isNewer &amp;&amp; !isSignificantlyLessAccurate &amp;&amp; isFromSameProvider) {
        return true;
    }
    return false;
}

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
      return provider2 == null;
    }
    return provider1.equals(provider2);
}
</pre>

<h2 id="TaskGetLastKnownLocation">Use getLastKnownLocation() Wisely</h2>

<p>The setup time for getting a reasonable location fix may not be acceptable for certain applications.  You should consider calling the {@link android.location.LocationManager#getLastKnownLocation(java.lang.String) getLastKnownLocation()} method which simply queries Android for the last location update previously received by any location providers.  Keep in mind that the returned location may be stale.  You should check the timestamp and accuracy of the returned location and decide whether it is useful for your application.  If you elect to discard the location update returned from {@link android.location.LocationManager#getLastKnownLocation(java.lang.String) getLastKnownLocation()} and wait for fresh updates from the location provider(s), you should consider displaying an appropriate message before location data is received.</p>

<h2 id="TaskTerminateUpdates">Terminate Location Updates</h2>

<p>When you are done with using location data, you should terminate location update to reduce
unnecessary consumption of power and network bandwidth.  For example, if the user navigates away
from an activity where location updates are displayed, you should stop location update by calling
{@link android.location.LocationManager#removeUpdates(android.location.LocationListener)
removeUpdates()} in {@link android.app.Activity#onStop()}.  ({@link android.app.Activity#onStop()}
is called when the activity is no longer visible.  If you want to learn more about activity
lifecycle, read up on the <a
href="{@docRoot}training/basics/activity-lifecycle/stopping.html">Stopping and Restarting an
Activity</a> lesson.</p>

<pre>
protected void onStop() {
    super.onStop();
    mLocationManager.removeUpdates(listener);
}
</pre>

<p class="note"><strong>Note:</strong> For applications that need to continuously receive and process location updates like a near-real time mapping application, it is best to incorporate the location update logic in a background service and make use of the system notification bar to make the user aware that location data is being used.</p>