public class

LocationClient

extends Object
implements GooglePlayServicesClient
java.lang.Object
   ↳ com.google.android.gms.location.LocationClient

Class Overview

The LocationClient is the main entry point for location related APIs, such as location and geofence.

Use the LocationClient to:

  • Connect and disconnect to Google Location Services.
  • Request/remove location update callbacks.
  • Request/remove geofences.

In order to establish a connection, call connect() and wait for the onConnected(android.os.Bundle) callback.

Summary

Nested Classes
interface LocationClient.OnAddGeofencesResultListener The listener for receiving callbacks when the operation to add geofences completes. 
interface LocationClient.OnRemoveGeofencesResultListener The listener for receiving callbacks when the operation to remove geofences completes. 
Constants
String KEY_LOCATION_CHANGED Key used for a Bundle extra holding a Location value when a location change is broadcast using a PendingIntent.
String KEY_MOCK_LOCATION Key used for the Bundle extra in Location object holding a boolean indicating whether the location was set using setMockLocation(Location).
Public Constructors
LocationClient(Context context, GooglePlayServicesClient.ConnectionCallbacks connectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener connectionFailedListener)
Creates a LocationClient.
Public Methods
void addGeofences(List<Geofence> geofences, PendingIntent pendingIntent, LocationClient.OnAddGeofencesResultListener listener)
Sets alerts to be notified when the device enters or exits one of the specified geofences.
void connect()
Connects the client to Google Play services.
void disconnect()
Closes the connection to Google Play services.
static int getErrorCode(Intent intent)
Returns the error code that explains the error that triggered this intent.
static int getGeofenceTransition(Intent intent)
Returns the transition type of geofence transition alert.
Location getLastLocation()
Returns the best most recent location currently available.
static List<Geofence> getTriggeringGeofences(Intent intent)
Returns a list of geofences that triggers this geofence transition alert.
static boolean hasError(Intent intent)
Whether an error triggered this intent.
boolean isConnected()
Checks if the client is currently connected to the service, so that requests to other methods will succeed.
boolean isConnecting()
Checks if the client is attempting to connect to the service.
boolean isConnectionCallbacksRegistered(GooglePlayServicesClient.ConnectionCallbacks listener)
Returns true if the specified listener is currently registered to receive connection events.
boolean isConnectionFailedListenerRegistered(GooglePlayServicesClient.OnConnectionFailedListener listener)
Returns true if the specified listener is currently registered to receive connection failed events.
void registerConnectionCallbacks(GooglePlayServicesClient.ConnectionCallbacks listener)
Registers a listener to receive connection events from this GooglePlayServicesClient.
void registerConnectionFailedListener(GooglePlayServicesClient.OnConnectionFailedListener listener)
Registers a listener to receive connection failed events from this GooglePlayServicesClient.
void removeGeofences(List<String> geofenceRequestIds, LocationClient.OnRemoveGeofencesResultListener listener)
Removes geofences by their request IDs.
void removeGeofences(PendingIntent pendingIntent, LocationClient.OnRemoveGeofencesResultListener listener)
Removes all geofences associated with the given pendingIntent.
void removeLocationUpdates(LocationListener listener)
Removes all location updates for the given location listener.
void removeLocationUpdates(PendingIntent callbackIntent)
Removes all location updates for the given pending intent.
void requestLocationUpdates(LocationRequest request, PendingIntent callbackIntent)
Requests location updates with a callback on the specified PendingIntent.
void requestLocationUpdates(LocationRequest request, LocationListener listener)
Requests location updates.
void requestLocationUpdates(LocationRequest request, LocationListener listener, Looper looper)
Requests location updates with a callback on the specified Looper thread.
void setMockLocation(Location mockLocation)
Sets the mock location to be used for the location provider.
void setMockMode(boolean isMockMode)
Sets whether or not the location provider is in mock mode.
void unregisterConnectionCallbacks(GooglePlayServicesClient.ConnectionCallbacks listener)
Removes a connection listener from this GooglePlayServicesClient.
void unregisterConnectionFailedListener(GooglePlayServicesClient.OnConnectionFailedListener listener)
Removes a connection failed listener from the GooglePlayServicesClient.
[Expand]
Inherited Methods
From class java.lang.Object
From interface com.google.android.gms.common.GooglePlayServicesClient

Constants

public static final String KEY_LOCATION_CHANGED

Key used for a Bundle extra holding a Location value when a location change is broadcast using a PendingIntent.

Constant Value: "com.google.android.location.LOCATION"

public static final String KEY_MOCK_LOCATION

Key used for the Bundle extra in Location object holding a boolean indicating whether the location was set using setMockLocation(Location). If the value is false this extra is not set.

Constant Value: "mockLocation"

Public Constructors

public LocationClient (Context context, GooglePlayServicesClient.ConnectionCallbacks connectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener connectionFailedListener)

Creates a LocationClient.

Parameters
context the context to use for the connection.
connectionCallbacks the callbacks invoked when the client is connected.
connectionFailedListener the listener which will be notified if the connection attempt fails.

Public Methods

public void addGeofences (List<Geofence> geofences, PendingIntent pendingIntent, LocationClient.OnAddGeofencesResultListener listener)

Sets alerts to be notified when the device enters or exits one of the specified geofences. If an existing geofence with the same request ID is already registered, the old geofence is replaced by the new one, and the new pendingIntent is used to generate intents for alerts.

onAddGeofencesResult(int, String[]) is called when geofences are successfully added or failed to be added. Refer to onAddGeofencesResult(int, String[]) for possible errors when adding geofences.

When a geofence transition (for example, entering or exiting) matches one of the transition filter (see setTransitionTypes(int)) in the given geofence list, an intent is generated using the given pending intent. You can call getGeofenceTransition(Intent) to get the transition type of this alert intent and call getTriggeringGeofences(Intent) to get the geofences that triggered this intent.

In case network location provider is disabled by the user, the geofence service will stop updating, all registered geofences will be removed and an intent is generated by the provided pending intent. In this case, hasError(Intent) returns true and getErrorCode(Intent) returns GEOFENCE_NOT_AVAILABLE.

This method requires ACCESS_FINE_LOCATION.

Parameters
geofences a list of geofences to be added. The geofences must be created using Geofence.Builder.
pendingIntent a pending intent that will be used to generate an intent when matched geofence transition is observed
listener the callback that receives the status code for this operation
Throws
SecurityException if the app does not have ACCESS_FINE_LOCATION permission
IllegalStateException if the connection to Google Play Store Services hasn't been established
IllegalArgumentException if geofences is null or empty
NullPointerException if intent or listener is null

public void connect ()

Connects the client to Google Play services. This method returns immediately, and connects to the service in the background. If the connection is successful, onConnected(Bundle) is called. On a failure, onConnectionFailed(ConnectionResult) is called.

public void disconnect ()

Closes the connection to Google Play services. No calls can be made on this object after calling this method.

public static int getErrorCode (Intent intent)

Returns the error code that explains the error that triggered this intent.

Parameters
intent the intent generated for alert
Returns

public static int getGeofenceTransition (Intent intent)

Returns the transition type of geofence transition alert.

Parameters
intent the intent generated for geofence alert
Returns
  • -1 if the intent is not generated for transition alert; Otherwise returns the GEOFENCE_TRANSITION_ flags value defined in Geofence.

public Location getLastLocation ()

Returns the best most recent location currently available.

If a location is not available, which should happen very rarely, null will be returned. The best accuracy available while respecting the location permissions will be returned.

This method provides a simplified way to get location. It is particularly well suited for applications that do not require an accurate location and that do not want to maintain extra logic for location updates.

public static List<Geofence> getTriggeringGeofences (Intent intent)

Returns a list of geofences that triggers this geofence transition alert.

Parameters
intent the intent generated for geofence alert
Returns
  • a list of geofences that triggers this geofence transition alert or null if the given intent is not generated for geofence transition alert

public static boolean hasError (Intent intent)

Whether an error triggered this intent.

Parameters
intent the intent generated for alert
Returns
  • true if an error triggered this intent otherwise false

public boolean isConnected ()

Checks if the client is currently connected to the service, so that requests to other methods will succeed. Applications should guard client actions caused by the user with a call to this method.

Returns
  • true if the client is connected to the service.

public boolean isConnecting ()

Checks if the client is attempting to connect to the service.

Returns
  • true if the client is attempting to connect to the service.

public boolean isConnectionCallbacksRegistered (GooglePlayServicesClient.ConnectionCallbacks listener)

Returns true if the specified listener is currently registered to receive connection events.

Parameters
listener The listener to check for.
Returns
  • true if the specified listener is currently registered to receive connection events.

public boolean isConnectionFailedListenerRegistered (GooglePlayServicesClient.OnConnectionFailedListener listener)

Returns true if the specified listener is currently registered to receive connection failed events.

Parameters
listener The listener to check for.
Returns
  • true if the specified listener is currently registered to receive connection failed events.

public void registerConnectionCallbacks (GooglePlayServicesClient.ConnectionCallbacks listener)

Registers a listener to receive connection events from this GooglePlayServicesClient. If the service is already connected, the listener's onConnected(Bundle) method will be called immediately. Applications should balance calls to this method with calls to unregisterConnectionCallbacks(ConnectionCallbacks) to avoid leaking resources.

If the specified listener is already registered to receive connection events, this method will not add a duplicate entry for the same listener, but will still call the listener's onConnected(Bundle) method if currently connected.

Note that the order of messages received here may not be stable, so clients should not rely on the order that multiple listeners receive events in.

Parameters
listener the listener where the results of the asynchronous connect() call are delivered.

public void registerConnectionFailedListener (GooglePlayServicesClient.OnConnectionFailedListener listener)

Registers a listener to receive connection failed events from this GooglePlayServicesClient. Unlike registerConnectionCallbacks(GooglePlayServicesClient.ConnectionCallbacks), if the service is not already connected, the listener's onConnectionFailed(ConnectionResult) method will not be called immediately. Applications should balance calls to this method with calls to unregisterConnectionFailedListener(OnConnectionFailedListener) to avoid leaking resources.

If the specified listener is already registered to receive connection failed events, this method will not add a duplicate entry for the same listener.

Note that the order of messages received here may not be stable, so clients should not rely on the order that multiple listeners receive events in.

Parameters
listener the listener where the results of the asynchronous connect() call are delivered.

public void removeGeofences (List<String> geofenceRequestIds, LocationClient.OnRemoveGeofencesResultListener listener)

Removes geofences by their request IDs. Request ID is specified when you create a Geofence by calling setRequestId(String).

onRemoveGeofencesByRequestIdsResult(int, String[]) is called when geofences are successfully removed or failed to be removed.

This method requires ACCESS_FINE_LOCATION.

Parameters
geofenceRequestIds a list of request IDs of geofences that need to be removed
listener the callback that receives the status code for this operation
Throws
IllegalArgumentException if geofenceRequestIds is null or empty
SecurityException if the app does not have ACCESS_FINE_LOCATION permission
IllegalStateException if the connection to Google Play Store Services hasn't been established
NullPointerException if listener is null

public void removeGeofences (PendingIntent pendingIntent, LocationClient.OnRemoveGeofencesResultListener listener)

Removes all geofences associated with the given pendingIntent.

Warning: please use FLAG_UPDATE_CURRENT rather than FLAG_CANCEL_CURRENT when creating the pending intent, otherwise you will not get the same pending intent you provided to addGeofences(List, PendingIntent, OnAddGeofencesResultListener) and thus the removal operation will remove nothing.

onRemoveGeofencesByPendingIntentResult(int, PendingIntent) is called when geofences are successfully removed or fail to be removed.

This method requires ACCESS_FINE_LOCATION.

Parameters
pendingIntent the pending intent associated with the geofences that need to be removed.
listener the callback that receives the status code for this operation
Throws
SecurityException if the app does not have ACCESS_FINE_LOCATION permission
IllegalStateException if the connection to Google Play Store Services hasn't been established
NullPointerException if intent or listener is null

public void removeLocationUpdates (LocationListener listener)

Removes all location updates for the given location listener.

Parameters
listener The listener to remove.

public void removeLocationUpdates (PendingIntent callbackIntent)

Removes all location updates for the given pending intent.

Parameters
callbackIntent The callback intent to remove.

public void requestLocationUpdates (LocationRequest request, PendingIntent callbackIntent)

Requests location updates with a callback on the specified PendingIntent.

This method is suited for the background use cases, more specifically for receiving location updates, even when the app has been killed by the system. In order to do so, use a PendingIntent for a started service. For foreground use cases, the LocationListener version of the method is recommended, see requestLocationUpdates(LocationRequest, LocationListener).

Any previous LocationRequests registered on this PendingIntent will be replaced.

Location updates are sent with a key of KEY_LOCATION_CHANGED and a Location value on the intent.

Parameters
request The location request for the updates.
callbackIntent A pending intent to be sent for each location update.

public void requestLocationUpdates (LocationRequest request, LocationListener listener)

Requests location updates.

This method is suited for the foreground use cases, more specifically for requesting locations while being connected to LocationClient. For background use cases, the PendingIntent version of the method is recommended, see requestLocationUpdates(LocationRequest, PendingIntent).

Any previous LocationRequests registered on this LocationListener will be replaced.

Callbacks for LocationListener will be made on the calling thread, which must already be a prepared looper thread, such as the main thread of the calling Activity. The variant of this method with a Looper is recommended for cases where the callback needs to happen on a specific thread. See requestLocationUpdates(LocationRequest, LocationListener, android.os.Looper).

Parameters
request The location request for the updates.
listener The listener for the location updates.

public void requestLocationUpdates (LocationRequest request, LocationListener listener, Looper looper)

Requests location updates with a callback on the specified Looper thread.

This method is suited for the foreground use cases,more specifically for requesting locations while being connected to LocationClient. For background use cases, the PendingIntent version of the method is recommended, see requestLocationUpdates(LocationRequest, PendingIntent).

Any previous LocationRequests registered on this LocationListener will be replaced.

Callbacks for LocationListener will be made on the specified thread, which must already be a prepared looper thread. For cases where the callback can happen on the calling thread, the variant of this method without a Looper can be used. See requestLocationUpdates(LocationRequest, LocationListener, android.os.Looper).

Parameters
request The location request for the updates.
listener The listener for the location updates.
looper The Looper object whose message queue will be used to implement the callback mechanism, or null to make callbacks on the calling thread.

public void setMockLocation (Location mockLocation)

Sets the mock location to be used for the location provider. This location will be used in place of any actual locations from the underlying providers (network or gps).

setMockMode(boolean) must be called and set to true prior to calling this method.

Care should be taken in specifying the timestamps as many applications require them to be monotonically increasing.

Parameters
mockLocation The mock location. Must have a minimum number of fields set to be considered a valild location, as per documentation in the Location class.
Throws
SecurityException if the ACCESS_MOCK_LOCATION permission is not present or the Settings.Secure.ALLOW_MOCK_LOCATION system setting is not enabled.

public void setMockMode (boolean isMockMode)

Sets whether or not the location provider is in mock mode.

The underlying providers (network and gps) will be stopped (except by direct LocationManager access), and only locations specified in setMockLocation(Location) will be reported. This will effect all location clients connected using the LocationClient, including geofencer clients (i.e. geofences can be triggered based on mock locations).

The client must remain connected in order for mock mode to remain active. If the client dies the system will return to its normal state.

Calls are not nested, and mock mode will be set directly regardless of previous calls.

Parameters
isMockMode If true the location provider will be set to mock mode. If false it will be returned to its normal state.
Throws
SecurityException if the ACCESS_MOCK_LOCATION permission is not present or the Settings.Secure.ALLOW_MOCK_LOCATION system setting is not enabled.

public void unregisterConnectionCallbacks (GooglePlayServicesClient.ConnectionCallbacks listener)

Removes a connection listener from this GooglePlayServicesClient. Note that removing a listener does not generate any callbacks.

If the specified listener is not currently registered to receive connection events, this method will have no effect.

Parameters
listener the listener to unregister.

public void unregisterConnectionFailedListener (GooglePlayServicesClient.OnConnectionFailedListener listener)

Removes a connection failed listener from the GooglePlayServicesClient. Note that removing a listener does not generate any callbacks.

If the specified listener is not currently registered to receive connection failed events, this method will have no effect.

Parameters
listener the listener to unregister.