Tổng quan về API hàng rào
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Trong API Nhận biết, khái niệm rào được lấy từ tính năng khoanh vùng địa lý, trong đó một khu vực địa lý hoặc khoanh vùng địa lý được xác định và ứng dụng sẽ nhận được lệnh gọi lại khi người dùng vào hoặc rời khỏi khu vực khoanh vùng địa lý. Fence API mở rộng khái niệm khoanh vùng địa lý để bao gồm nhiều điều kiện ngữ cảnh khác ngoài khoảng cách địa lý. Ứng dụng sẽ nhận được lệnh gọi lại bất cứ khi nào trạng thái ngữ cảnh chuyển đổi. Ví dụ: nếu ứng dụng của bạn xác định một hàng rào cho tai nghe, thì ứng dụng đó sẽ nhận được lệnh gọi lại khi tai nghe được cắm và khi tai nghe được rút ra.
Bạn có thể sử dụng Fence API để xác định hàng rào dựa trên các tín hiệu ngữ cảnh, chẳng hạn như sau:
- Vị trí hiện tại của người dùng (vĩ độ/kinh độ)
- Hoạt động hiện tại của người dùng, chẳng hạn như đi bộ hoặc lái xe.
- Các điều kiện dành riêng cho thiết bị, chẳng hạn như liệu bạn có cắm tai nghe hay không.
- Khoảng cách đến các beacon ở gần
Fence API cho phép bạn kết hợp nhiều tín hiệu ngữ cảnh để tạo hàng rào bằng toán tử boolean AND
, OR
và NOT
. Sau đó, ứng dụng của bạn sẽ nhận được lệnh gọi lại bất cứ khi nào các điều kiện của hàng rào được đáp ứng. Sau đây là một số ví dụ về hàng rào có thể có:
- Người dùng cắm tai nghe và bắt đầu đi bộ.
- Người dùng đi vào khoanh vùng địa lý 100 mét trước 5 giờ chiều vào ngày thường.
- Người dùng đi vào phạm vi của một beacon BLE cụ thể.
Ví dụ sau đây cho biết cách xác định một hàng rào kích hoạt bất cứ khi nào người dùng đi bộ:
AwarenessFence walkingFence = DetectedActivityFence.during(DetectedActivityFence.WALKING);
Sau khi xác định hàng rào, bạn phải làm như sau:
- Gọi
updateFences
để đăng ký hàng rào nhận lệnh gọi lại.
- Xác định lệnh gọi lại có thể được gọi khi trạng thái hàng rào thay đổi.
Ví dụ sau đây cho thấy một phương thức tạo và đăng ký hàng rào. Trong ví dụ này, một lớp con tuỳ chỉnh của BroadcastReceiver
được dùng để xử lý ý định khi hàng rào được kích hoạt.
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);
}
}
}
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2025-08-31 UTC.
[null,null,["Cập nhật lần gần đây nhất: 2025-08-31 UTC."],[[["\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 }"]]