Register a Fence

Your app receives a callback via PendingIntent whenever the state of a fence changes. Your app must register each fence before it can be used.

Register a fence

To register a fence, call FenceApi.updateFences(), and use FenceUpdateRequest.Builder() to construct a fence update request, calling addFence() for each fence to add. The following things are required to register (and unregister) a fence:

  • A Google Play Services API Client instance.
  • An AwarenessFence instance (the fence itself).
  • A PendingIntent to handle state changes.
  • A fence key (a string which identifies the fence, and maps to an AwarenessFence/PendingIntent pair).

The following code example shows a method that calls updateFences() to register a fence:

// Declare variable for PendingIntent
private PendingIntent mPendingIntent;

protected void registerFence(final String fenceKey, final AwarenessFence fence) {
    Awareness.FenceApi.updateFences(
          mGoogleApiClient,
          new FenceUpdateRequest.Builder()
              .addFence(fenceKey, fence, mPendingIntent)
              .build())
          .setResultCallback(new ResultCallback<Status>() {
              @Override
              public void onResult(@NonNull Status status) {
                  if(status.isSuccess()) {
                      Log.i(TAG, "Fence was successfully registered.");
                      queryFence(fenceKey);
                  } else {
                      Log.e(TAG, "Fence could not be registered: " + status);
                  }
              }
          });
}

You can create multiple fences with unique fence keys by calling addFence() multiple times. You can use as many PendingIntents as you need to, but it is preferable to use a single PendingIntent for all fence callbacks. If you call addFence() using a fence key that has already been registered, the AwarenessFence and PendingIntent values are overwritten for that key.

Unregister a fence

To unregister a fence, call FenceApi.updateFences(), and use FenceUpdateRequest.Builder() to construct a fence update request, calling removeFence().

protected void unregisterFence(final String fenceKey) {
    Awareness.FenceApi.updateFences(
            mGoogleApiClient,
            new FenceUpdateRequest.Builder()
                    .removeFence(fenceKey)
                    .build()).setResultCallback(new ResultCallbacks<Status>() {
        @Override
        public void onSuccess(@NonNull Status status) {
            Log.i(TAG, "Fence " + fenceKey + " successfully removed.");
        }

        @Override
        public void onFailure(@NonNull Status status) {
            Log.i(TAG, "Fence " + fenceKey + " could NOT be removed.");
        }
    });
}

Next step: Manage Fence Callbacks

Send feedback about...

assistant
Google Awareness API