AI-generated Key Takeaways
-
Your app receives a callback via
PendingIntentwhenever a fence's state changes, and each fence must be registered before use. -
To register a fence, use
FenceClientandFenceUpdateRequest.Builder(), callingaddFence()for each fence with a unique fence key that maps to anAwarenessFence-PendingIntentpair. -
Unregistering a fence involves calling
getFenceClient().updateFences()and usingFenceUpdateRequest.Builder()withremoveFence()for the specific fence key. -
You can add and remove fences within the same
FenceUpdateRequest, and using an existing fence key withaddFence()will overwrite its associatedAwarenessFenceandPendingIntentvalues.
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
AwarenessFenceinstance, which is the fence itself. - A
PendingIntentto handle state changes. - A fence key, which is a string that identifies the fence and maps to an
AwarenessFence-PendingIntentpair.
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.