Register a fence

Your app receives a callback by 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, use the FenceClient, and to construct a FenceUpdateRequest, use FenceClient.updateFences(). Call addFence() for each fence to add.

The following are required to register, and unregister, a fence:

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

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

    Awareness.getFenceClient(this).updateFences(new FenceUpdateRequest.Builder()
        .addFence(FENCE_KEY, exercisingWithHeadphonesFence, mPendingIntent)
        .build())
        .addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.i(TAG, "Fence was successfully registered.");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.e(TAG, "Fence could not be registered: " + e);
            }
        });

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

Unregister a fence

To unregister a fence, call getFenceClient().updateFences(), and use FenceUpdateRequest.Builder() to construct a fence update request. Then call removeFence(), as the following example shows:

 Awareness.getFenceClient(this).updateFences(new FenceUpdateRequest.Builder()
     .removeFence(FENCE_KEY)
     .build())
     .addOnSuccessListener(new OnSuccessListener<Void>() {
         @Override
         public void onSuccess(Void aVoid) {
             Log.i(TAG, "Fence was successfully unregistered.");
         }
     })
     .addOnFailureListener(new OnFailureListener() {
         @Override
         public void onFailure(@NonNull Exception e) {
             Log.e(TAG, "Fence could not be unregistered: " + e);
         }
     });

Next step: Manage fence callbacks.