Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
public class MainActivity extends Activity implements
LocationClient.OnAddGeofencesResultListener {
private LocationClient mLocationClient;
protected void onCreate(Bundle savedInstanceState) {
mLocationClient = new LocationClient(this, this, this);
protected void onStart() {
public void onConnected(Bundle dataBundle) {
// this callback will be invoked when the client is connected
// from now on, you can fetch current location and listen to location updates
// fetch the current location
// note that this method might return null in a very rare case (i.e. location is not available)
Location location = mLocationClient.getLastLocation();
// start listening to location updates
// this is suitable for foreground listening, with the onLocationChanged() invoked for location updates
LocationRequest locationRequest = LocationRequest.create()
mLocationClient.requestLocationUpdates(locationRequest, this);
// this is suitable for background location tracking
// your MyLocationHandler service will still be triggered even if your app is killed by the system
PendingIntent pendingIntent = PendingIntent.getService(this, 0,
new Intent(this, MyLocationHandler.class),
mLocationClient.requestLocationUpdates(locationRequest, pendingIntent);
// adds geofencing
ArrayList<Geofence> geofences = new ArrayList<Geofence>();
geofences.add(new Geofence.Builder()
.setCircularRegion(60.1708, 24.9375, 1000)
.setLoiteringDelay(30000) // GEOFENCE_TRANSITION_DWELL will be notified 30 seconds after the device enters the area
PendingIntent pendingIntent2 = PendingIntent.getService(this, 0,
new Intent(this, MyGeofenceHandler.class),
mLocationClient.addGeofences(geofences, pendingIntent2, this);
public void onDisconnected() {
// this callback will be invoked when the client is disconnected
// it might happen e.g. when the location service crashes
// you can't access until it's connected again
public void onConnectionFailed(ConnectionResult connectionResult) {
// this callback will be invoked when the connection attempt fails
if (connectionResult.hasResolution()) {
// Google Play services can fix the issue
try {
connectionResult.startResolutionForResult(this, 0);
} catch (IntentSender.SendIntentException e) {
// it happens if the resolution intent has been canceled,
// or is no longer able to execute the request.
} else {
// Google Play services has no idea how to fix the issue
// it rarely happens for the location service
public void onLocationChanged(Location location) {
// this callback is invoked when location updates
public void onAddGeofencesResult (int statusCode, String[] geofenceRequestIds) {
// this callback is invoked when geofences are added, either succeed or fail
protected void onStop() {
if (mLocationClient.isConnected())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment