在 Awareness API 中,圍欄的概念源自地理圍欄,其中定義了地理區域或地理圍欄,而應用程式會在使用者進入或離開地理圍欄區域時收到回呼。Fence API 擴充了地理圍欄的概念,除了地理位置相近之外,還納入許多其他情境條件。只要情境狀態轉換,應用程式就會收到回呼。舉例來說,如果應用程式為耳機定義邊界,則會在耳機插入和拔除時收到回呼。
您可以使用 Fence API,根據情境訊號定義邊界,例如:
- 使用者目前的位置 (緯度/經度)
- 使用者目前從事的活動,例如步行或開車。
- 裝置專屬條件,例如耳機是否已插入。
- 與附近的訊號發送器距離
Fence API 可讓您結合多個內容信號,使用 AND
、OR
和 NOT
布林運算子建立柵欄。接著,只要符合邊界條件,應用程式就會收到回呼。以下列舉幾個可能的圍欄範例:
- 使用者接上耳機並開始步行。
- 使用者在工作日下午 5 點前進入 100 公尺地理範圍。
- 使用者進入特定 BLE 訊號塔的範圍。
以下範例說明如何定義邊界,讓邊界在使用者步行時啟用:
AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
定義邊界後,您必須執行以下操作:
- 呼叫
updateFences
以註冊邊界,以便接收回呼。 - 定義可在圍欄狀態變更時叫用的回呼。
以下範例顯示建立及註冊邊界的方法。在這個範例中,系統會使用 BroadcastReceiver
的自訂子類別,在觸發邊界時處理意圖。
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);
}
});
public class FenceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
FenceState fenceState = FenceState.extract(intent);
if (TextUtils.equals(fenceState.getFenceKey(), FENCE_KEY)) {
String fenceStateStr;
switch (fenceState.getCurrentState()) {
case FenceState.TRUE:
fenceStateStr = "true";
break;
case FenceState.FALSE:
fenceStateStr = "false";
break;
case FenceState.UNKNOWN:
fenceStateStr = "unknown";
break;
default:
fenceStateStr = "unknown value";
}
mLogFragment.getLogView().println("Fence state: " + fenceStateStr);
}
}
}