如果您在 Manifest 文件中指定 BroadCastReceiver 就足够了。
<receiver>
即使在声明 Manifest条目之后,也不必在代码中注册它。想想平台如何处理你只在 Manifest 文件中注册它的活动(如果没有我们得到 ActivityNotFoundException),就像广播也可以只在 Manifest 文件中注册一样。
您需要像这样声明接收者:
<receiver android:name=".MyFenceReceiver" >
<intent-filter>
<action android:name="android.intent.action.FENCE_RECEIVER_ACTION" />
</intent-filter>
</receiver>
扩展 BroadcastReceiver 类。
public class MyFenceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
FenceState fenceState = FenceState.extract(intent);
if (TextUtils.equals(fenceState.getFenceKey(), "geofence")) {
switch(fenceState.getCurrentState()) {
case FenceState.TRUE:
break;
case FenceState.FALSE:
break;
case FenceState.UNKNOWN:
break;
}
}
}
}
https://developer.android.com/guide/topics/manifest/receiver-element.html中的更多信息