圍欄會定義一或多個情境條件,讓應用程式做出反應。圍欄狀態變更時,應用程式會收到回呼。
圍欄分為兩種類型:原始圍欄 (代表一組基本情境信號) 和組合圍欄 (使用布林運算子結合多個原始圍欄)。所有圍欄都是 AwarenessFence 的例項。
建立原始圍欄
原始柵欄代表一組基本比對內容信號,定義於 awareness.fence 套件中。以下範例說明如何建立簡單的圍欄,當偵測到使用者的活動為 WALKING 時,圍欄會 TRUE,否則會 FALSE:
AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
在上述範例中,DetectedActivityFence 是透過呼叫 during 建立,這表示只要使用者處於 WALKING 狀態,圍欄就會處於 TRUE 狀態。
回應轉換
除了 TimeFence 以外,每種原始圍欄類型也可以在情境狀態轉換時暫時觸發。舉例來說,您可以設定 DetectedActivityFence,在使用者starting或stopping活動時暫時觸發。轉換圍欄會先處於 TRUE 狀態幾秒,然後再次轉為 FALSE。
建立組合圍欄
組合圍欄會使用布林運算子,結合多種原始圍欄類型。以下範例說明如何建立組合圍欄,在使用者步行且插入耳機時啟用:
// 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
);
AND、OR 和 NOT 的巢狀樹狀結構有效,因此可以採用任何圍欄布林組合。以下範例顯示,當使用者從目前位置移動超過 100 公尺,「或」自目前時間起經過一小時以上,就會觸發圍欄。
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));
下一步:註冊圍欄。