Fence API 概览
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
在 Awareness API 中,围栏的概念源自地理围栏,其中定义了地理区域(即地理围栏),当用户进入或离开地理围栏区域时,应用会收到回调。Fence API 扩展了地理围栏的概念,除了地理位置相近之外,还包含许多其他情境条件。每当上下文状态发生转换时,应用都会收到回调。例如,如果您的应用为耳机定义了围栏,则会在耳机插入和拔出时收到回调。
您可以使用 Fence API 根据情境信号定义边界,例如:
- 用户的当前位置(纬度/经度)
- 用户当前的活动,例如步行或驾车。
- 设备专用条件,例如耳机是否已插入。
- 与附近信标的距离
借助 Fence API,您可以组合多个情境信号,使用 AND
、OR
和 NOT
布尔运算符创建屏障。然后,每当满足栅栏条件时,您的应用都会收到回调。可能的围栏示例如下:
- 用户插入耳机并开始步行。
- 用户在工作日下午 5 点之前进入 100 米的地理围栏。
- 用户进入特定 BLE 信标的范围。
以下示例展示了如何定义一个每当用户步行时都会激活的围栏:
AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
定义栅栏后,您必须执行以下操作:
以下示例展示了用于创建和注册栅栏的方法。在此示例中,系统使用 BroadcastReceiver
的自定义子类来处理触发栅栏时的 intent。
Awareness.getFenceClient(this).updateFences(new FenceUpdateRequest.Builder()
.addFence(FENCE_KEY, exercisingWithHeadphonesFence, mPendingIntent)
.build())
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Log.i(TAG, "Fence was successfully registered.");
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Fence could not be registered: " + e);
}
});
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);
}
}
}
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-31。
[null,null,["最后更新时间 (UTC):2025-08-31。"],[[["\u003cp\u003eThe Awareness API uses fences, inspired by geofencing, to trigger app callbacks based on various context signals like location, user activity, and device conditions.\u003c/p\u003e\n"],["\u003cp\u003eYou can define fences using the Fence API by combining context signals with boolean operators (AND, OR, NOT) to create specific conditions.\u003c/p\u003e\n"],["\u003cp\u003eApps receive callbacks when a fence's conditions are met, such as when a user starts walking while wearing headphones or enters a designated area.\u003c/p\u003e\n"],["\u003cp\u003eTo utilize fences, register them using \u003ccode\u003eupdateFences\u003c/code\u003e and define a callback (e.g., using a \u003ccode\u003eBroadcastReceiver\u003c/code\u003e) to handle fence state changes.\u003c/p\u003e\n"]]],["The Fence API expands upon geofencing by allowing apps to define fences based on various context conditions. These include user location, activity, device status, and proximity to beacons. Fences can combine multiple context signals using boolean operators, triggering callbacks when conditions are met. To use a fence, you define it, register it via `updateFences`, and create a callback (like a `BroadcastReceiver`) to respond to state changes. The callback's state will reflect `TRUE`, `FALSE`, or `UNKNOWN`.\n"],null,["# Fence API overview\n\nIn the Awareness API, the concept of *fences* is taken from\n[geofencing](https://developer.android.com/training/location/geofencing),\nin which a geographic region, or *geofence*, is defined, and an app receives\ncallbacks when a user enters or leaves the geofence region. The Fence API expands on\nthe concept of geofencing to include many other context conditions in addition\nto geographical proximity. An app receives callbacks whenever the context\nstate transitions. For example, if your app defines a fence for headphones,\nit gets callbacks when the headphones are plugged in and when they're\nunplugged.\n\nYou can use the\n[Fence API](/android/reference/com/google/android/gms/awareness/Awareness#getFenceClient(android.app.Activity))\nto define fences based on context signals, such as the following:\n\n- The user's current location (latitude/longitude)\n- The user's current activity, like walking or driving.\n- Device-specific conditions, such as whether the headphones are plugged in.\n- Proximity to nearby beacons\n\nThe Fence API lets you combine multiple\n[context signals](/awareness/overview#context-types)\nto create fences with `AND`, `OR`, and `NOT` boolean operators. Your app then\nreceives callbacks whenever the fence conditions are met. Some examples of\npossible fences include the following:\n\n- User plugs in headphones and starts to walk.\n- User enters a 100-meter geofence before 5 PM on a weekday.\n- User enters range of a specific BLE beacon.\n\nThe following example shows how to define a fence that activates whenever\nthe user walks: \n\n AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);\n\nOnce you've defined a fence, you must do the following:\n\n- Call [`updateFences`](/android/reference/com/google/android/gms/awareness/FenceClient#updateFences(com.google.android.gms.awareness.fence.FenceUpdateRequest)) to register the fence to receive callbacks.\n- Define a callback that can be invoked when the fence state changes.\n\nThe following example shows a method that creates and registers a fence. In\nthis example, a custom subclass of `BroadcastReceiver` is used to handle the\nintent when the fence is triggered. \n\n Awareness.getFenceClient(this).updateFences(new FenceUpdateRequest.Builder()\n .addFence(FENCE_KEY, exercisingWithHeadphonesFence, mPendingIntent)\n .build())\n .addOnSuccessListener(new OnSuccessListener\u003cVoid\u003e() {\n @Override\n public void onSuccess(Void aVoid) {\n Log.i(TAG, \"Fence was successfully registered.\");\n }\n })\n .addOnFailureListener(new OnFailureListener() {\n @Override\n public void onFailure(@NonNull Exception e) {\n Log.e(TAG, \"Fence could not be registered: \" + e);\n }\n });\n public class FenceReceiver extends BroadcastReceiver {\n @Override\n public void onReceive(Context context, Intent intent) {\n\n FenceState fenceState = FenceState.extract(intent);\n\n if (TextUtils.equals(fenceState.getFenceKey(), FENCE_KEY)) {\n String fenceStateStr;\n switch (fenceState.getCurrentState()) {\n case FenceState.TRUE:\n fenceStateStr = \"true\";\n break;\n case FenceState.FALSE:\n fenceStateStr = \"false\";\n break;\n case FenceState.UNKNOWN:\n fenceStateStr = \"unknown\";\n break;\n default:\n fenceStateStr = \"unknown value\";\n }\n mLogFragment.getLogView().println(\"Fence state: \" + fenceStateStr);\n }\n }\n }"]]