建立圍欄

圍欄會定義一或多個應用程式可做出反應的內容條件。 圍欄狀態變更時,應用程式會收到回呼。

圍欄有兩種:原始圍欄 (代表基本的一組情境信號) 和組合圍欄 (使用布林值運算子組合多個原始圍欄)。所有柵欄都是 AwarenessFence 的執行個體。

建立基本柵欄

原始柵欄代表基本的一組情境信號,定義於 awareness.fence 套件中。以下範例說明如何建立簡單的柵欄,當系統偵測到使用者活動為 WALKING 時,該柵欄會 TRUE,否則會 FALSE

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

在上例中,DetectedActivityFence 是透過呼叫 during 建立,這表示只要使用者處於 WALKING 狀態,圍欄就會處於 TRUE 狀態。

對轉場效果做出反應

除了 TimeFence 以外,每種基本柵欄類型都可以在情境狀態轉換時暫時觸發。舉例來說,您可以設定 DetectedActivityFence,在使用者startingstopping 活動時暫時觸發。轉換圍欄會處於 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
);

ANDORNOT 的巢狀樹狀結構皆有效,因此可使用任意布林值組合的圍欄。以下範例顯示的柵欄會在使用者移動超過目前位置 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));

後續步驟:註冊圍欄