How to check if a fence key is registered for Awareness API?

417 Views Asked by At

I have 2 questions about Googles Awareness Fences API:

  1. Do we have a method to check if a fence with a given fence key is registered?
  2. What will happen if I accidentally register 2 fences with the same fence key ?
1

There are 1 best solutions below

0
On BEST ANSWER
  1. To check if a fence is registered, make a FenceQueryRequest and check if FenceStateMap contains the fence key.

Here is example code:

protected void queryFence(final String fenceKey) {
    Awareness.FenceApi.queryFences(mGoogleApiClient,
            FenceQueryRequest.forFences(Arrays.asList(fenceKey)))
            .setResultCallback(new ResultCallback<FenceQueryResult>() {
                @Override
                public void onResult(@NonNull FenceQueryResult fenceQueryResult) {
                    if (!fenceQueryResult.getStatus().isSuccess()) {
                        Log.e(TAG, "Could not query fence: " + fenceKey);
                        return;
                    }
                    FenceStateMap map = fenceQueryResult.getFenceStateMap();
                    if (!map.getFenceKeys().contains(fenceKey)) {
                      // Fence is not registered. 
                    }
                }
            });
}
  1. If you register 2 fences with the same fence key, the second fence will replace the first fence. See the FenceUpdateRequest documentation.