管理圍欄回呼

註冊圍欄後,應用程式必須新增回呼,以便在觸發圍欄時回應。為此,您可以使用 BroadcastReceiver 的子類別來處理柵欄中的 Intent 方法。

您必須先註冊圍欄,才能新增圍欄的回呼。

建立 BroadcastReceiver 的子類別

以下範例顯示擴充 BroadcastReceiverFenceReceiver 類別。該類別會實作 BroadcastReceiver.onReceive() 回呼方法,以處理應用程式建立的柵欄的所有 Intent 方法。收到 Intent 時,系統會使用 FenceState.extract() 方法取得柵欄狀態,並將其傳遞至回呼。

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);
        }
    }
}