In this document
- Connect to Google Play Services
- Request Location Updates
- Detect On-Board GPS
- Handle Disconnection Events
- Handle Location Not Found
- Synchronize Data
Dependencies and prerequisites
- Android 4.3 (API Level 18) or higher on the handset device
- Google Play services 6.1 or higher
- An Android Wear device
See also
Location awareness on wearable devices enables you to create apps that give users a better understanding of their geographic position, movement and what's around them. With the small form factor and glanceable nature of a wearable device, you can build low-friction apps that record and respond to location data.
Some wearable devices include a GPS sensor that can retrieve location data without another tethered device. However, when you request location data in a wearable app, you don't have to worry about where the location data originates; the system retrieves the location updates using the most power-efficient method. Your app should be able to handle loss of location data, in case the wear device loses connection with its paired device and does not have a built-in GPS sensor.
This document shows you how to check for on-device location sensors, receive location data, and monitor tethered data connections.
Note: The article assumes that you know how to use the Google Play services API to retrieve location data. For more information, see Making Your App Location-Aware.
Connect to Google Play Services
Location data on wearable devices is obtained though the Google Play services location APIs. You
use the
FusedLocationProviderApi
and its accompanying classes to obtain this data.
To access location services, create an instance of
GoogleApiClient
, which is
the main entry point for any of the Google Play services APIs.
Caution: Do not use the existing Location APIs in the Android framework. The best practice for retrieving location updates is through the Google Play services API as outlined in this article.
To connect to Google Play services, configure your app to create an instance of
GoogleApiClient
:
- Create an activity that specifies an implementation for the interfaces
ConnectionCallbacks
,OnConnectionFailedListener
, andLocationListener
. - In your activity's
onCreate()
method, create an instance ofGoogleApiClient
and add the Location service. - To gracefully manage the lifecycle of the connection, call
connect()
in theonResume()
method anddisconnect()
in theonPause()
method.
The following code example shows an implementation of an activity that implements the
LocationListener
interface:
public class WearableMainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { private GoogleApiClient mGoogleApiClient; ... @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addApi(Wearable.API) // used for data layer API .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); } @Override protected void onResume() { super.onResume(); mGoogleApiClient.connect(); ... } @Override protected void onPause() { super.onPause(); ... mGoogleApiClient.disconnect(); } }
For more information on connecting to Google Play services, see Accessing Google APIs.
Request Location Updates
After your app has connected to the Google Play services API, it is ready to start receiving
location updates. When the system invokes the
onConnected()
callback for your client, you build the location data request as
follows:
- Create a
LocationRequest
object and set any options using methods likesetPriority()
. - Request location updates using
requestLocationUpdates()
. - Remove location updates using
removeLocationUpdates()
in theonPause()
method.
The following example shows how to retrieve and remove location updates:
@Override public void onConnected(Bundle bundle) { LocationRequest locationRequest = LocationRequest.create() .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setInterval(UPDATE_INTERVAL_MS) .setFastestInterval(FASTEST_INTERVAL_MS); LocationServices.FusedLocationApi .requestLocationUpdates(mGoogleApiClient, locationRequest, this) .setResultCallback(new ResultCallback() { @Override public void onResult(Status status) { if (status.getStatus().isSuccess()) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "Successfully requested location updates"); } } else { Log.e(TAG, "Failed in requesting location updates, " + "status code: " + status.getStatusCode() + ", message: " + status.getStatusMessage()); } } }); } @Override protected void onPause() { super.onPause(); if (mGoogleApiClient.isConnected()) { LocationServices.FusedLocationApi .removeLocationUpdates(mGoogleApiClient, this); } mGoogleApiClient.disconnect(); } @Override public void onConnectionSuspended(int i) { if (Log.isLoggable(TAG, Log.DEBUG)) { Log.d(TAG, "connection to location client suspended"); } }
Now that you have enabled location updates, the system calls the onLocationChanged()
method with the updated location at the interval specified in
setInterval()
Detect On-Board GPS
Not all wearables have a GPS sensor. If your user goes out for a run and leaves their phone at home, your wearable app cannot receive location data through a tethered connection. If the wearable device does not have a sensor, you should detect this situation and warn the user that location functionality is not available.
To determine whether your Android Wear device has a built-in GPS sensor, use the
hasSystemFeature()
method. The following code detects whether the device has built-in GPS when you start an activity:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); if (!hasGps()) { Log.d(TAG, "This hardware doesn't have GPS."); // Fall back to functionality that does not use location or // warn the user that location function is not available. } ... } private boolean hasGps() { return getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION_GPS); }
Handle Disconnection Events
Wearable devices relying on a tethered connection for location data may lose their connections abruptly. If your wearable app expects a constant stream of data, you must handle the disconnection based upon where that data is interrupted or unavailable. On a wearable device with no onboard GPS sensor, loss of location data occurs when the device loses its tethered data connection.
In cases where your app depends on a tethered data connection for location data and the wear device does not have a GPS sensor, you should detect the loss of that connection, warn the user, and gracefully degrade the functionality of your app.
To detect the loss of a tethered data connection:
- Extend a
WearableListenerService
that lets you listen for important data layer events. - Declare an intent filter in your Android manifest to notify the system about your
WearableListenerService
. This filter allows the system to bind your service as needed.<service android:name=".NodeListenerService"> <intent-filter> <action android:name="com.google.android.gms.wearable.BIND_LISTENER" /> </intent-filter> </service>
- Implement the
onPeerDisconnected()
method and handle cases of whether or not the device has built-in GPS.public class NodeListenerService extends WearableListenerService { private static final String TAG = "NodeListenerService"; @Override public void onPeerDisconnected(Node peer) { Log.d(TAG, "You have been disconnected."); if(!hasGPS()) { // Notify user to bring tethered handset // Fall back to functionality that does not use location } } ... }
Handle Location Not Found
When the GPS signal is lost, you can still retrieve the last known location using
getLastLocation()
. This method can be helpful in situations where you are unable to
get a GPS fix, or when your wearable doesn't have built-in GPS and loses its connection with the
phone.
The following code uses
getLastLocation()
to retrieve the last known location if available:
Location location = LocationServices.FusedLocationApi .getLastLocation(mGoogleApiClient);
Synchronize Data
If your wearable app records data using the built-in GPS, you may want to synchronize
the location data with the handset. With the LocationListener
, you
implement the onLocationChanged()
method to detect and record the location as it changes.
The following code for wearable apps detects when the location changes and uses the data layer API to store the data for later retrieval by your phone app:
@Override public void onLocationChanged(Location location) { ... addLocationEntry(location.getLatitude(), location.getLongitude()); } private void addLocationEntry(double latitude, double longitude) { if (!mSaveGpsLocation || !mGoogleApiClient.isConnected()) { return; } mCalendar.setTimeInMillis(System.currentTimeMillis()); // Set the path of the data map String path = Constants.PATH + "/" + mCalendar.getTimeInMillis(); PutDataMapRequest putDataMapRequest = PutDataMapRequest.create(path); // Set the location values in the data map putDataMapRequest.getDataMap() .putDouble(Constants.KEY_LATITUDE, latitude); putDataMapRequest.getDataMap() .putDouble(Constants.KEY_LONGITUDE, longitude); putDataMapRequest.getDataMap() .putLong(Constants.KEY_TIME, mCalendar.getTimeInMillis()); // Prepare the data map for the request PutDataRequest request = putDataMapRequest.asPutDataRequest(); // Request the system to create the data item Wearable.DataApi.putDataItem(mGoogleApiClient, request) .setResultCallback(new ResultCallback() { @Override public void onResult(DataApi.DataItemResult dataItemResult) { if (!dataItemResult.getStatus().isSuccess()) { Log.e(TAG, "Failed to set the data, " + "status: " + dataItemResult.getStatus() .getStatusCode()); } } }); }
For more information on how to use the Data Layer API, see the Sending and Syncing Data guide.