Create a fence

Stay organized with collections Save and categorize content based on your preferences.

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 with the use of 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 the creation of a simple fence that's 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 a call to 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 they turn FALSE again.

Create a combination fence

Combination fences combine multiple primitive fence types with the use of boolean operators. The following example shows the creation of a combination fence that activates when the user walks 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 any boolean combination of fences is possible. The following example shows a fence that's 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.