• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Getting the Last Known Location
2trainingnavtop=true
3@jd:body
4
5<div id="tb-wrapper">
6  <div id="tb">
7
8    <h2>This lesson teaches you how to</h2>
9    <ol>
10      <li><a href="#setup">Set Up Google Play Services</a></li>
11      <li><a href="#permissions">Specify App Permissions</a></li>
12      <li><a href="#play-services">Connect to Google Play Services</a></li>
13      <li><a href="#last-known">Get the Last Known Location</a></li>
14    </ol>
15
16    <h2>You should also read</h2>
17    <ul>
18      <li>
19        <a href="{@docRoot}google/play-services/setup.html">Setting up Google Play
20        Services</a>
21      </li>
22    </ul>
23
24    <h2>Try it out</h2>
25    <ul>
26      <li>
27        <a href="https://github.com/googlesamples/android-play-location/tree/master/BasicLocationSample" class="external-link">BasicLocationSample</a>
28      </li>
29    </ul>
30  </div>
31</div>
32
33<p>Using the Google Play services location APIs, your app can request the last
34  known location of the user's device. In most cases, you are interested in the
35  user's current location, which is usually equivalent to the last known
36  location of the device.</p>
37
38<p>Specifically, use the
39  <a href="{@docRoot}reference/com/google/android/gms/location/FusedLocationProviderApi.html">fused
40  location provider</a> to retrieve the device's last known location. The fused
41  location provider is one of the location APIs in Google Play services. It
42  manages the underlying location technology and provides a simple API so that
43  you can specify requirements at a high level, like high accuracy or low power.
44  It also optimizes the device's use of battery power.</p>
45
46<p>This lesson shows you how to make a single request for the location of a
47  device using the
48  <a href="{@docRoot}reference/com/google/android/gms/location/FusedLocationProviderApi.html#getLastLocation(com.google.android.gms.common.api.GoogleApiClient)">{@code getLastLocation()}</a>
49  method in the fused location provider.
50
51<h2 id="setup">Set Up Google Play Services</h2>
52
53<p>To access the fused location provider, your app's development project must
54  include Google Play services. Download and install the Google Play services
55  component via the <a href="{@docRoot}tools/help/sdk-manager.html">SDK
56  Manager</a> and add the library to your project. For details, see the guide to
57  <a href="{@docRoot}google/play-services/setup.html">Setting Up Google Play
58  Services</a>.</p>
59
60<h2 id="permissions">Specify App Permissions</h2>
61
62<p>Apps that use location services must request location permissions. Android
63  offers two location permissions:
64  {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_COARSE_LOCATION}
65  and
66  {@link android.Manifest.permission#ACCESS_FINE_LOCATION ACCESS_FINE_LOCATION}.
67  The permission you choose determines the accuracy of the location returned by
68  the API. If you specify
69  {@link android.Manifest.permission#ACCESS_COARSE_LOCATION ACCESS_COARSE_LOCATION},
70  the API returns a location with an accuracy approximately equivalent to a city
71  block.</p>
72
73<p>This lesson requires only coarse location. Request this permission with the
74  {@code uses-permission} element in your app manifest, as the following code
75  snippet shows:
76
77<pre>
78&lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
79    package="com.google.android.gms.location.sample.basiclocationsample" &gt;
80
81  &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/&gt;
82&lt;/manifest&gt;
83</pre>
84
85<h2 id="play-services">Connect to Google Play Services</h2>
86
87<p>To connect to the API, you need to create an instance of the
88  Google Play services API client. For details about using the client, see
89  the guide to
90  <a href="{@docRoot}google/auth/api-client.html#Starting">Accessing Google
91  APIs</a>.
92</p>
93
94<p>In your activity's {@link android.app.Activity#onCreate onCreate()} method,
95  create an instance of Google API Client, using the
96  <a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.Builder.html">{@code GoogleApiClient.Builder}</a> class to add the
97  <a href="{@docRoot}reference/com/google/android/gms/location/LocationServices.html">
98  {@code LocationServices}</a>
99  API, as the following code snippet shows.</p>
100
101<pre>
102// Create an instance of GoogleAPIClient.
103if (mGoogleApiClient == null) {
104    mGoogleApiClient = new GoogleApiClient.Builder(this)
105        .addConnectionCallbacks(this)
106        .addOnConnectionFailedListener(this)
107        .addApi(LocationServices.API)
108        .build();
109}
110</pre>
111
112<p>To connect, call
113<a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient#connect()">
114  {@code connect()}</a>
115  from the activity's
116  <a href="{@docRoot}reference/android/app/Activity.html#onStart()">{@code onStart()}</a>
117  method. To disconnect, call
118  <a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient#disconnect()">
119  {@code disconnect()}</a> from the activity's
120  <a href="{@docRoot}reference/android/app/Activity.html#onStop()">
121  {@code onStop()}</a> method. The following snippet shows an example of how
122  to use both of these methods.
123  </p>
124
125<pre>
126protected void onStart() {
127    mGoogleApiClient.connect();
128    super.onStart();
129}
130
131protected void onStop() {
132    mGoogleApiClient.disconnect();
133    super.onStop();
134}
135</pre>
136
137<h2 id="last-known">Get the Last Known Location</h2>
138
139<p>Once you have connected to Google Play services and the location services
140  API, you can get the last known location of a user's device. When your app is
141  connected to these you can use the fused location provider's
142  <a href="{@docRoot}reference/com/google/android/gms/location/FusedLocationProviderApi.html#getLastLocation(com.google.android.gms.common.api.GoogleApiClient)">{@code getLastLocation()}</a>
143  method to retrieve the device location. The precision of the location returned
144  by this call is determined by the permission setting you put in your app
145  manifest, as described in the <a href="#permissions">Specify App
146  Permissions</a> section of this document.</p>
147
148<p>To request the last known location, call the
149  <a href="{@docRoot}reference/com/google/android/gms/location/FusedLocationProviderApi.html#getLastLocation(com.google.android.gms.common.api.GoogleApiClient)">{@code getLastLocation()}</a>
150  method, passing it your instance of the
151  <a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.html">{@code GoogleApiClient}</a>
152  object. Do this in the
153  <a href="{@docRoot}reference/com/google/android/gms/common/api/GoogleApiClient.ConnectionCallbacks.html#onConnected(android.os.Bundle)">{@code onConnected()}</a>
154  callback provided by Google API Client, which is called when the client is
155  ready. The following code snippet illustrates the request and a simple
156  handling of the response:</p>
157
158<pre>
159public class MainActivity extends ActionBarActivity implements
160        ConnectionCallbacks, OnConnectionFailedListener {
161    ...
162    &#64;Override
163    public void onConnected(Bundle connectionHint) {
164        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
165                mGoogleApiClient);
166        if (mLastLocation != null) {
167            mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
168            mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
169        }
170    }
171}
172</pre>
173
174<p>The
175  <a href="{@docRoot}reference/com/google/android/gms/location/FusedLocationProviderApi.html#getLastLocation(com.google.android.gms.common.api.GoogleApiClient)">{@code getLastLocation()}</a>
176  method returns a
177  <a href="{@docRoot}reference/android/location/Location.html">{@code Location}</a>
178  object from which you can retrieve the latitude and longitude coordinates of a
179  geographic location. The location object returned may be null in rare cases
180  when the location is not available.</p>
181
182<p>The next lesson,
183  <a href="change-location-settings.html">Changing Location Settings</a>, shows
184  you how to detect the current location settings, and prompt the user to
185  change settings as appropriate for your app's requirements.</p>
186