注册栅栏后,您的应用必须添加一个在触发栅栏时进行响应的回调。为此,您可以使用 BroadcastReceiver
的子类处理栅栏中的 Intent
方法。
在将栅栏添加到栅栏之前,您必须先注册栅栏。
创建 BroadcastReceiver 的子类
以下示例展示了扩展 BroadcastReceiver
的 FenceReceiver
类。该类实现 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);
}
}
}