Create a Fence

A fence defines one or more context conditions to which your app can react. When a fence's state changes, your app receives a callback. There are two types of fences: primitive fences which represent the basic set of context signals, and combination fences which combine multiple primitive fences by using boolean operators. All fences are instances of AwarenessFence.

Create a primitive fence

Primitive fences, which represent the basic set of context signals, are defined in the awareness.fence package. The following example shows creating a simple fence that is TRUE when the user's detected activity is WALKING, and FALSE otherwise:

AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);

In the preceding example, the DetectedActivityFence was created by calling during, which means the fence is in the TRUE state whenever the user is WALKING.

React to transitions

Each primitive fence type (with the exception of TimeFence) can also be triggered momentarily when the context state transitions. For example, you can set a DetectedActivityFence to momentarily trigger when a user is starting or stopping an activity. Transition fences are in the TRUE state for a few seconds before turning FALSE again.

Create a combination fence

Combination fences combine multiple primitive fence types by using boolean operators. The following example shows creating a combination fence that activates when the user is walking AND the headphones are plugged in:

// Create the primitive fences.
AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
AwarenessFence headphoneFence = HeadphoneFence.during(HeadphoneState.PLUGGED_IN);

// Create a combination fence to AND primitive fences.
AwarenessFence walkingWithHeadphones = AwarenessFence.and(
      walkingFence, headphoneFence
);

Nested trees of AND, OR and NOT are valid, so that any boolean combination of fences is possible. The following example shows a fence that is triggered when a user moves more than 100 meters from the current location, OR over an hour has elapsed since the current time.

double currentLocationLat;  // current location latitude
double currentLocationLng;  // current location longitude
long nowMillis = System.currentTimeMillis();
long oneHourMillis = 1L * 60L * 60L * 1000L;

AwarenessFence orExample = AwarenessFence.or(
        AwarenessFence.not(LocationFence.in(
                currentLocationLat,
                currentLocationLng,
                100.0,
                100.0,
                0L)),
        TimeFence.inInterval(nowMillis + oneHourMillis, Long.MAX_VALUE));

Next step: Register a Fence

Send feedback about...

assistant
Google Awareness API