Manage Fence Callbacks

Once a fence has been registered, your app must add a callback to respond when the fence is triggered. You can do this by using a subclass of BroadcastReceiver to handle Intents from fences.

Before adding callbacks to a fence, the fence must first be registered.

Create a subclass of BroadcastReceiver

The following example shows the MyFenceReceiver class which extends BroadcastReceiver. The class should implement the BroadcastReceiver.onReceive() callback method to handle all Intents that originate from fences created by your app. When an Intent is received, the FenceState.extract() method is used to get the fence state and pass it to the callback.

// Declare variable for MyFenceReceiver class.
private MyFenceReceiver mMyFenceReceiver;

// Initialize fence variables in onCreate().
protected void onCreate(Bundle savedInstanceState) {
  ...
  Intent intent = new Intent(FENCE_RECEIVER_ACTION);
  mMyFenceReceiver = new MyFenceReceiver();
  registerReceiver(mMyFenceReceiver, new IntentFilter(FENCE_RECEIVER_ACTION));
  ...
}

// Extend the BroadcastReceiver class.
public class MyFenceReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        FenceState fenceState = FenceState.extract(intent);

        if (TextUtils.equals(fenceState.getFenceKey(), "headphoneFence")) {
            switch(fenceState.getCurrentState()) {
                case FenceState.TRUE:
                    Log.i(TAG, "Headphones are plugged in.");
                    break;
                case FenceState.FALSE:
                    Log.i(TAG, "Headphones are NOT plugged in.");
                    break;
                case FenceState.UNKNOWN:
                    Log.i(TAG, "The headphone fence is in an unknown state.");
                    break;
            }
        }
    }
}

Send feedback about...

assistant
Google Awareness API